home *** CD-ROM | disk | FTP | other *** search
Wrap
/*** The contents of this file are subject to the Mozilla Public License Version 1.1 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.mozilla.org/MPL/ Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the specific language governing rights and limitations under the License. The Original Code is StumbleUpon code. The Initial Developer of the Original Code is StumbleUpon. Portions created by StumbleUpon are Copyright (C) 2002-2007 StumbleUpon. All Rights Reserved. Original Author: Geoff Smith <geoff@stumbleupon.com> Contributor(s): Garrett Camp <gmc@stumbleupon.com> Joe Walp <joewalp@yahoo.com> Manpreet Singh (loonyone.stumbleupon.com) Questions/Comments? Please send them here: http://www.stumbleupon.com/feedback.php Copyright notes: 1. No code contributed by Manpreet Singh remains in the codebase. 2. Regardless of intellectual property claims, Manpreet Singh supports changing the license from MPL to MPL/GPL/LGPL tri-license if other contributors so choose. For reference: http://www.mozilla.org/MPL/boilerplate-1.1/mpl-tri-license-txt 3. For additional intellectual property considerations, search for [IP:] and [kudos:] in the code. ***/ //************** GLOBALS ****************/ var su_private_label = "2010020301"; var su_source_label = "AM"; var su_log_communication = true; var su_log_sync = false; var su_log_polling = false; var su_log_resource_cfd = false; var su_log_mimetype = false; var su_force_migrate_prerelease = ((su_private_label.indexOf("ALPHA") == 0) || (su_private_label.indexOf("BETA") == 0)); var su_test_stumblethru_update = false; var su_test_info = false; var su_test_extra_init = false; var su_test_campus_dist = false; var su_test_facebookhome_prompt = false; var su_test_searchpage_prompt = false; var su_test_mimetype = false; var su_disable_sync = false; var su_enable_freereporting = true; var su_enable_message_log = (su_private_label.indexOf("ALPHA") == 0); var mozbar_version = "3.63"; var su_servername = 'stumbleupon.com'; var su_serverhttp = 'http://www.' + su_servername + '/'; var su_serverhttps = 'https://www.' + su_servername + '/'; var su_base_url = su_serverhttp; var su_ds = null; var su_host = null; var su_stumbleReporter = null; var su_window_time_ms = (new Date()).getTime(); var stumbleid = 0; var stumblepass = ""; var su_visited_login_page = false; var su_promo_mode = false; var su_login_initialized = false; var su_stumble_throttled = false; var su_info_spec = null; var su_tag_instructions = "Search or Tag here"; var su_tagged_folder_name = "Unfiled/Tagged"; var su_video_tagid = 1196; var su_enable_hashed_password; var su_prev_nick = null; var su_random_delay = 0; var su_cacheTimer = 0; var su_prefetcher; var su_last_typed_tag = 0; // timestamp of the last time you typed a new tag var su_old_search = ""; // the search you had before we change due to tagging var su_url_has_tag = false; var su_search_service_id = null; var su_drawer_timers = new Object(); var su_visited_searchbox = 0; var su_toggling_toolbar = false; var su_moving_toolbar = false; //var su_check_referral_flag = 0; var su_check_referral_timer = null; var su_process_rarely_timer = null; var su_dist_time_timer = null; var su_toolbar_disabled = false; var su_quote = ""; var su_photoblogimage = null; var su_ratings = new Object(); // array of url->su_ratings var su_tag_lists_by_url = new Object(); // object url->tag_list var su_tags = new Array(); // array of objects with properties 'url' and 'tag_list' var su_selected_category = "0"; var su_stumble_async_context = null; var su_stumblevideo_toolbar_rate = false; var su_pending_stumblevideo_stumble = false; var su_pending_stumblevideo_rate_context = null; var stumbled_url = ""; // your last stumble var su_redirect_url = ""; var stumbled_redirect; // the url your last stumble got redirected to var su_previous_query_category = ""; var su_stumble_action_count = 0; var stumbles; // queue of urls to be stumbled upon in the future var su_user_interests = new Array(); // array of intersts the user is signed up for var su_catnames = new Array(); // array of catid -> catname (topics.csv) var su_catids = new Object(); // array of catid -> catname (topics.csv) var su_foldernames = new Array(); // folder names var su_topicfolders = new Array(); // maps topic id's to su_foldernames var su_queries; // list of last 100 queries var su_notifier_dialog = null; var su_preference_dialog = null; var su_customize_invoked_from_preference_dialog = false; var su_uninstall_scheduled = false; var su_remove_data_scheduled = false; // The following are used by the keybinding routines, and some are // accessed by the preferenceDialog and by the keybinding migration // routine. var su_keys_by_keyspec = new Object(); var su_commands_by_keyspec; var su_removed_keybindings_by_keyspec = new Object(); var su_keyids_by_eventkeycode = new Object(); var su_chars_by_keyid = new Object(); var su_keyids_by_char = new Object(); var su_recent_keypress_modifiers; var su_load_image_count = 0; var su_has_searchbox = false; // for efficiency var su_keep_searchbox_focus = false; var su_searchbox_was_focused = false; // used by the searchbox click kludge var su_gui_initialized = false; var su_searchlinks_dialog_detail = null; // The following are used by the toolbar location and overflow routines. var su_sidebar_was_hidden; var su_old_toolbar_x; var su_old_toolbar_position = null; var su_old_toolbar_position_group = null; var su_reflow_delayed = false; var su_overflow_popup_open = false; var su_referred_popup_open = false; var su_moving_splitter = false; var su_toolbar_justification; var su_bookmarks_sibling_loc = null; var su_persist_queue = new Array(); var su_resize_window_width = 0; var su_resize_window_dirty = false; var su_referral_menu_dirty = true; var su_referral_popup_open = false; var su_refreshing_referral_menu = false; var su_dyn_channels_dirty = true; var su_mode_more_popup_open = false; var su_refreshing_dyn_channels = false; var su_pagemeta_dirty = true; var su_refreshing_pagemeta = false; var su_refreshing_category_selector = false; var su_blocked_category_selector_refresh_pending = false; var su_new_install = false; // true for first run after install var su_new_upgrade = false; // true for first run after upgrade var su_new_user = false; // true between getid.php and interests_after.php var su_prev_version; // set when su_new_upgrade is true var su_migrate_toolbar_position_scheduled = false; var su_d_rec_rating = false; // Handle StumbleUpon sidebar (conversation bar) var su_sidebar_enabled = false; // Disabled by default //************** END GLOBALS ****************/ //********* INCLUDES *****************// function su_include(uri) { try { su_get_service( "@mozilla.org/moz/jssubscript-loader;1", "mozIJSSubScriptLoader") .loadSubScript(uri); } catch (e) { if ((uri != "chrome://stumbleupon/content/extra.js") || su_test_extra_init) su_log_error("INCLUDE", e, uri); } } var su_toolbar_api = { processCommands: function(commands) { su_process_commands(commands); } } su_include("chrome://stumbleupon/content/migrate.js"); su_include("chrome://stumbleupon/content/prefetcher.js"); //********* END INCLUDES *****************// //********* INITIALIZATION *****************// // See also the bottom of the file for additional initialization. function su_load_categories() { su_catnames = su_ds.getDictionary("catid:topic_name"); su_catids = su_ds.getDictionary("topic_name:catid"); su_topicfolders = su_ds.getDictionary("catid:folder_name"); su_foldernames = su_ds.getAlphaSupertopicNames(); // Load topics.csv // okay, let's try topics.csv that came with the xpi //!!! bah, let's not bother updating topics.csv over the net // it changes so infrequently /* alert(catdat); //!!! var catdat = su_read_file_global("topics.csv"); var da = new Date(); var timenow = da.getTime(); var oneweek = 24 * 60 * 60 * 7 * 1000; // javascript stores time in milliseconds var last_categories = su_ds.getValue("$categories_dat"); if (catdat == "" || timenow - last_categories > oneweek) { // We need to hit the server and grab topics.csv //!!! mozilla's caching is on crack (it doesn't even check server to see if there's a new vesrion unless we create a salt!) var res = su_post_url_server("topics.csv", null); // If we got it, make it catdat and write it to disk if (res.status == 200) { catdat = res.response; //!!! su_write_file_global("topics.csv", catdat); } // Write last_categories last_categories = timenow; su_ds.setValue("$categories_dat", timenow); su_ds.flushPrefs(); } */ } function su_is_server_page(url, path) { return ((url.indexOf(su_serverhttp + path) == 0) || (url.indexOf(su_serverhttps + path) == 0)); } function su_process_slclicks(force) { if (su_ds.getValue("#slprocessed") && (! force)) return; su_ds.setValue("#slprocessed", true); var slclicks = su_ds.selectAllRows("slclick"); var slstats = su_ds.getValue("$slstats").split(":"); var profile = new Object(); var url_page1 = new Object(); var url_page2 = new Object(); var tag_page = new Object(); var result = new Object(); var result_dt = new Object(); var result_dc = new Object(); var result_ds = new Object(); var result_dl = new Object(); var result_df = new Object(); var result_dm = new Object(); var result_dz = new Object(); var index_clicked = new Array(); var index_friend_clicked = new Array(); var i; for (i = 0; i < 10; i++) { index_clicked[i] = 0; index_friend_clicked[i] = 0; } // fields // --------------- // userid // timestamp // session query num // query term count // result count // decorated count // friend decorated count // first decorated num // url_page1 clicked count // comment clicked count // url_page2 clicked count // topic clicked count // result clicked count // thumbed result clicked count (dt) // nickname result clicked count (df) // multinickname result clicked count (dm) // comment result clicked count (dc) // comment level > 0 result clicked count (dl) // starred > 1 result clicked count (ds) // topic result clicked count (dz) var slq; for (i = 0; i < slclicks.length; i++) { var row = slclicks[i]; slq = row.q; if (row.i < 10) { if (row.r && row.df) index_friend_clicked[row.i]++; else if (row.r) index_clicked[row.i]++; } if (row.u) url_page1[slq] = (url_page1[slq]) ? (url_page1[slq] + 1) : 1; if (row.p) profile[slq] = (profile[slq]) ? (profile[slq] + 1) : 1; if (row.n) url_page2[slq] = (url_page2[slq]) ? (url_page2[slq] + 1) : 1; if (row.z) tag_page[slq] = (tag_page[slq]) ? (tag_page[slq] + 1) : 1; if (row.r) result[slq] = (result[slq]) ? (result[slq] + 1) : 1; if (row.r && row.dt) result_dt[slq] = (result_dt[slq]) ? (result_dt[slq] + 1) : 1; if (row.r && row.dc) result_dc[slq] = (result_dc[slq]) ? (result_dc[slq] + 1) : 1; if (row.r && (row.ds > 1)) result_ds[slq] = (result_ds[slq]) ? (result_ds[slq] + 1) : 1; if (row.r && row.dl) result_dl[slq] = (result_dl[slq]) ? (result_dl[slq] + 1) : 1; if (row.r && row.df) result_df[slq] = (result_df[slq]) ? (result_df[slq] + 1) : 1; if (row.r && (row.df > 1)) result_dm[slq] = (result_dm[slq]) ? (result_dm[slq] + 1) : 1; if (row.r && row.dz) result_dz[slq] = (result_dz[slq]) ? (result_dz[slq] + 1) : 1; } var stats = ""; for (i = 0; i < slstats.length; i++) { if (slstats[i] == "") continue; slq = slstats[i].split("\t")[1]; if (! url_page1[slq]) url_page1[slq] = 0; if (! profile[slq]) profile[slq] = 0; if (! url_page2[slq]) url_page2[slq] = 0; if (! tag_page[slq]) tag_page[slq] = 0; if (! result[slq]) result[slq] = 0; if (! result_dt[slq]) result_dt[slq] = 0; if (! result_dc[slq]) result_dc[slq] = 0; if (! result_ds[slq]) result_ds[slq] = 0; if (! result_dl[slq]) result_dl[slq] = 0; if (! result_df[slq]) result_df[slq] = 0; if (! result_dm[slq]) result_dm[slq] = 0; if (! result_dz[slq]) result_dz[slq] = 0; stats += stumbleid + "\t" + slstats[i] + "\t" + url_page1[slq] + "\t" + profile[slq] + "\t" + url_page2[slq] + "\t" + tag_page[slq] + "\t" + result[slq] + "\t" + result_dt[slq] + "\t" + result_df[slq] + "\t" + result_dm[slq] + "\t" + result_dc[slq] + "\t" + result_dl[slq] + "\t" + result_ds[slq] + "\t" + result_dz[slq] + "\n"; } var istats = ""; var slistats = su_ds.getValue("$slistats").split(":"); var slidfstats = su_ds.getValue("$slidfstats").split(":"); for (i = 0; i < 10; i++) { istats += (i + 1) + "\t" + slistats[i] + "\t" + slidfstats[i] + "\t" + index_clicked[i] + "\t" + index_friend_clicked[i] + "\n" } if (stats == "") return; su_ds.globals.sls = new Array(); su_ds.globals.sluqh = new Object(); su_ds.globals.sltih = new Object(); su_ds.setValue("$slstats", ""); su_ds.setValue("$slistats", "0:0:0:0:0:0:0:0:0:0"); su_ds.setValue("$slidfstats", "0:0:0:0:0:0:0:0:0:0"); su_ds.deleteAllRows("slclick"); su_ds.flushPrefs(); var params = ""; params = su_arp(params, "slstats", stats); params = su_arp(params, "slindexstats", istats); params = su_arp(params, "f", su_ds.getValue("$form")); var context = new Object(); context.quiet = true; su_post_url_server_async( "slstats.php", params, 15000, su_generic_done, context); } function su_get_random_int(min, max) { return Math.floor(Math.random() * (max - min + 1)) + min; } // initializes user-specific configuration that doesn't involve gui // elements function su_load_data1(new_profile) { //!!! We can migrate from flat files to mozStorage after that // feature is mature. We ought to be able to get rid of the // length limits on these data stores for clients that include // the embedded database. -- JW stumbled_url = ""; su_redirect_url = ""; stumbled_redirect = ""; // su_dd("reset", 2); stumbles = new Array(); su_ratings = new Object(); su_migrate_profile(new_profile); // make random delay... // this is to avoid a race condition in hitting stumbles.php // and hitting recommend.php to check_referral // after X+su_random_delay seconds ... ( up to 5 minutes) su_random_delay = Math.floor(Math.random()*300); su_stumble_action_count = 0; try { su_prefetcher.stop(); su_prefetcher.clearTargets(); su_prefetcher.passMax = su_ds.getValue("$prefetcher_pass_max"); su_prefetcher.pass1TimeoutInterval = su_ds.getValue("$prefetcher_pass_1_timeout_ms"); su_prefetcher.pass2TimeoutInterval = su_ds.getValue("$prefetcher_pass_2_timeout_ms"); su_prefetcher.pass3TimeoutInterval = su_ds.getValue("$prefetcher_pass_3_timeout_ms"); if (su_ds.getValue("$prefetcher_skip_resources")) su_prefetcher.mode = "DOM"; else su_prefetcher.mode = "complete"; su_prefetcher.addEventListener("progress-start", su_handle_prefetch_load_start); // If noscript is installed and the version is less than 1.9.8.4, then disable // the prefetcher. We do this because those versions have a bug which will cause // the prefetcher to open up a bunch of extra tabs. So we disable the // prefetcher if one of those versions of noscript is installed. Technically, // the problematic versions are < 1.9.7.9, but then there was a regression around // 1.9.8.1 that caused the problem again, but it was fixed again in 1.9.8.4, so we just // disable prefetcher on anything earlier than 1.9.8.4. var noscript_version = su_get_noscript_enabled_version(); if(noscript_version) { var minVersion = su_ds.getValue("@min_noscript_for_prefetch"); var result = su_dotversion_compare(noscript_version, minVersion); if(result && (result < 0)) { su_prefetcher.setQueueLock(true); } } } catch (e) { su_log_error("INIT PREFETCHER"); } su_stumbleReporter.start(); setTimeout(function (win) { win.su_load_ratings(); }, 0, window); try { su_load_stumbles(null); } catch (e) { su_log_error("LOAD STUMBLES", e); } try { su_load_categories(); } catch (e) { su_log_error("LOAD CATEGORIES", e); } try { su_load_user_interests(); } catch (e) { su_log_error("LOAD INTERESTS", e); } su_tags = new Array(); su_tag_lists_by_url = new Object(); setTimeout(function (win) { win.su_load_tags(null); }, 0, window); su_queries = new Array(); setTimeout(function (win) { win.su_load_queries(); }, 0, window); if (su_ds.getValue("@whitelist_upon_load")) { try { su_update_noscript_whitelists(); } catch (e) { su_log_error("INIT WHITELIST", e); } } su_ds.flushPrefs(); } function su_update_noscript_whitelists() { if (! su_ds.isPrefDefined("noscript.filterXExceptions")) return; var str = su_ds.getValue("noscript.filterXExceptions"); var exceptions = str.split("\n"); var regsafeServer = su_servername.replace(/\./g, "\\."); var filter_str = "^(http|https)://[a-z0-9\\-]+\\." + regsafeServer + "/"; var i; var found = false; for (i = 0; i < exceptions.length; i++) { if (exceptions[i] == filter_str) { found = true; break; } } if (! found) { exceptions.push(filter_str); str = exceptions.join("\n"); su_ds.setValue("noscript.filterXExceptions", str); } if ((typeof noscriptUtil) != "object") return; if (noscriptUtil.service && noscriptUtil.service.setJSEnabled && ((typeof noscriptUtil.service.setJSEnabled) == "function")) { noscriptUtil.service.setJSEnabled(su_servername, true); noscriptUtil.service.setJSEnabled("recaptcha.net", true); } su_ds.flushPrefs(); } // populates the stumbles array using content from file 'stumbleurls' function su_load_stumbles(url_to_exclude) { stumbles = new Array(); // Load stumbleurls (queue of urls to be stumbled upon) var unseen = su_read_file_user("stumbleurls"); var commands = unseen.split("\n"); try { if (su_ds.getValue("$last_incat") == su_previous_query_category) su_prefetcher.fetchAheadDepth = su_ds.getValue("$prefetcher_fetch_depth_in_query"); else su_prefetcher.fetchAheadDepth = su_ds.getValue("$prefetcher_fetch_depth_in_topic"); } catch (e) {} var found_url_to_exclude = false; var i; var url_detail; var target; for (i = 0; i < commands.length; i++) { if (!commands[i].match(/^(http|https|ftp):/i)) continue; url_detail = su_deserialize_url_command_params(commands[i], true); // Skip any old stumbles that don't have a public id if(!url_detail.publicid) continue; target = url_detail.actual_url ? url_detail.actual_url : url_detail.url; if ((target == url_to_exclude) && (! found_url_to_exclude)) { // exclude only the first instance of url_to_exclude found_url_to_exclude = true; continue; } try { if (su_is_404_status(su_prefetcher.getHttpResponseStatus(target))) { su_report_404(target, su_prefetcher.getHttpResponseStatus(target)); continue; } } catch (e) {} stumbles.push(commands[i]); // Don't prefetch against stumbleupon.com. if (target.indexOf(su_base_url) == 0) continue; // Don't prefetch profiles. if (su_get_profile_nickname(target)) continue; // Don't prefetch 'is_sound' urls. if (su_is_sound(target)) continue; // Don't prefetch sponsored stumbles. if (url_detail.cluster_type == 3) continue; // Don't prefetch referrals. if (url_detail.cluster_type == 4) continue; if (! url_detail.referrer) { if (su_is_adult_category(url_detail.catid)) url_detail.referrer = target; else if (su_ds.getValue("@enable_refer")) url_detail.referrer = "http://www.stumbleupon.com/refer.php?url=" + encodeURIComponent(target); else url_detail.referrer = "about:blank"; } try { su_prefetcher.addTarget(url_detail); } catch (e) { su_log_error("PREFETCHER 1", e); } } } // populates su_ratings using content from file 'stumblerating' function su_load_ratings() { su_ratings = new Object(); // load ratings var stumblecat = su_read_file_user("stumblerating"); var splitcat = stumblecat.split("\n"); for (var i = 0; i < splitcat.length; i++) { if (splitcat[i] == "") continue; var split2 = splitcat[i].split(" "); su_ratings[split2[0]] = split2[1]; } } // populates su_user_interests using content from pref 'interests' function su_load_user_interests() { su_user_interests = new Array(); // Load su_user_interests var stumbleseen = su_ds.getValue("$interests"); var splitseen = stumbleseen.split(" "); var i; for (i = 0; i < splitseen.length; i++) { if (splitseen[i] == "") continue; if (splitseen[i] == "toXMLRPCParam") continue; su_user_interests[splitseen[i]] = 1; } } // populates su_tags and su_tag_lists_by_url using content of the // stumbletags file function su_load_tags(url_to_exclude) { su_tags = new Array(); su_tag_lists_by_url = new Object(); var stumblecat = su_read_file_user("stumbletags"); var splitcat = stumblecat.split("\n"); for (var i = 0; i < splitcat.length; i++) { if (splitcat[i] == "") continue; var split2 = splitcat[i].split("\t"); var o = new Object(); o.url = split2[0]; o.tag_list = split2[1]; if ((o.url != url_to_exclude) && (o.url.indexOf("about:") != 0)) { su_tag_lists_by_url[o.url] = o.tag_list; su_tags.push(o); } } } // stores content of su_tags into the stumbletags file function su_store_tags() { var towrite = ""; for (var i = 0; (i < su_tags.length) && (i < su_ds.getValue("$tag_history_depth")); i++) towrite += su_tags[i].url + "\t" + su_tags[i].tag_list + "\n"; su_write_file_user("stumbletags", towrite); } // populates su_queries using content of the stumblequeries file function su_load_queries() { su_queries = new Array(); var stumblequeries = su_read_file_user("stumblequeries"); if (stumblequeries != "") su_queries = stumblequeries.split("\n"); // !! This is an inefficient method to get rid of the empty last // element due to the trailing linefeed in the file, but we'll // leave it this way for now, as it contributes robustness. -- JW for (var i = 0; i < su_queries.length; i++) { if (su_queries[i] == "") su_queries.splice(i, 1); } } // stores content of su_queries in the stumblequeries file function su_store_queries() { var towrite = ""; for (var i = 0; (i < su_queries.length) && (i < su_ds.getValue("$query_history_depth")); i++) towrite += su_queries[i] + "\n"; su_write_file_user("stumblequeries", towrite); } // initializes user-specific configuration that involves gui elements function su_load_data2(force_update) { su_get_element("su_searchbox").autocompleteDatasource = { getResults : function () { var searchbox = su_get_element("su_searchbox"); return su_get_autocomplete_results( su_ds.getValue("$autocomplete_type"), searchbox.value, searchbox.maxRows, new Array()); } }; // su_update_verified_reporting(false); su_update_referred(false); su_check_referral(force_update); su_process_rarely(force_update, false); if (force_update) { //!!! 1. Move contacts into getstate.php //!!! 2. Sync tag & person subscriptions? su_import_contacts(); su_get_state(false); } // Store this stumbleid in the ids list. The list is ordered from // most recently used to least recently used. -- JW var id_list = su_ds.getValue("@id_list"); var splitids = id_list.split(":"); var id_list_new = stumbleid + ":"; var i; for (i = 0; i < splitids.length; i++) { if (splitids[i] == "") continue; var line = splitids[i]; if (line != stumbleid) id_list_new += splitids[i] + ":"; } su_ds.setValue("@id_list", id_list_new); su_ds.flushPrefs(); su_init_keybinding_globals(); su_configure_toolbar(false); su_close_all_messages(); // Check to see when the url changes su_add_progress_listener(); // Upload any pending old stumbles su_upload_stumbles(); window.addEventListener("keyup", su_handle_window_keyup, false); window.addEventListener("keypress", su_handle_window_keypress, false); window.addEventListener("mousedown", su_handle_window_mousedown, true); su_ds.addEventListener("resourceinstalled", su_handle_resource_installed, false); su_download_favs(false); su_process_command_queue(); } function su_process_command_queue() { if (! su_host.places) return; // wait for places migration to finish if (su_ds.getValue("#migrating_places")) return; var context; if (su_ds.getValue("#command_queue_context")) return; var db = su_ds.getDatabase(); var sql; var result; sql = "SELECT seqid FROM command_queue WHERE priority>0 ORDER BY priority DESC, seqid LIMIT 1"; result = db.query(sql); if (result.length == 0) { su_ds.setValue("#download_favs_detail", null); // su_ds.setValue("#command_queue_context", null); return; } context = new Object(); su_ds.setValue("#command_queue_context", context); context.priority == null; context.command_rows = null; context.processed_idx = 0; context.download_favs_detail = null; // context.abort = false; setTimeout(su_process_command_queue2, 200, context); } function su_process_command_queue2(context) { var db = su_ds.getDatabase(); var sql; var seqid; var command; var row; var detail; var val; // 1. grab a set of commands if (! context.command_rows) { sql = "SELECT priority,seqid,command FROM command_queue WHERE priority>0 ORDER BY priority DESC, seqid LIMIT 1000"; context.command_rows = db.query(sql); context.processed_idx = 0; } // 2. check whether we're done. // if ((context.command_rows.length == 0) || context.abort) if (context.command_rows.length == 0) { su_ds.setValue("#command_queue_context", null); // moving out of favs if (context.download_favs_detail) { su_set_download_favs_enabled(true); context.download_favs_detail = null; } setTimeout(su_process_command_queue, 0); return; } row = context.command_rows[context.processed_idx]; if (context.download_favs_detail && (row.priority != 16000)) { // moving out of favs su_set_download_favs_enabled(true); context.download_favs_detail = null; } else if ((context.priority != 16000) && (row.priority == 16000)) { // moving into favs su_set_download_favs_enabled(false); detail = su_ds.getValue("#download_favs_detail"); if (! detail) { detail = su_ds.getValue("$download_favs_detail"); su_ds.setValue("#download_favs_detail", detail); } context.download_favs_detail = detail; } context.priority = row.priority; if (context.download_favs_detail) { detail = context.download_favs_detail; detail.apply_count++; if ((detail.applied_count % 1000) == 0) { su_ds.setValue("$download_favs_detail", detail); su_ds.flushPrefs(); } if (su_preference_dialog) { val = 5 + Math.round((45 * (detail.download_count / detail.download_target_count)) + (45 * (detail.apply_count / detail.apply_target_count))); el = su_preference_dialog.ownerDocument.getElementById("download_progress"); if (el && (val != el.value)) el.setAttribute("value", val); } } // 3. process the command su_process_command(row.command, context); // 4. remove it from the queue sql = "DELETE FROM command_queue WHERE seqid=" + db.v(row.seqid); db.query(sql); context.processed_idx++; if (context.command_rows.length == context.processed_idx) context.command_rows = null; setTimeout(su_process_command_queue2, 50, context); } function su_set_download_favs_enabled(enabled) { var el; var doc; var sync; if (! su_preference_dialog) return; doc = su_preference_dialog.ownerDocument; sync = doc.getElementById("sync_bm_meta").checked; if (enabled) doc.getElementById("download_progress").value = 0; doc.getElementById("download_start").disabled = (! sync) || (! enabled); doc.getElementById("download_stop").disabled = (! sync) || enabled; } // used during init to set hidden states for top-level toolbar // element function su_init_toolbar_element_visibility() { if ((stumbleid == 0) && su_promo_mode) { su_set_visible("su_start", true); su_set_visible("su_login", true); su_set_visible("su_stumble", false); su_set_visible("su_sites_promo", true); su_set_visible("su_friends", true); su_set_visible("su_thumbup", true); su_set_visible("su_thumbdown", false); su_get_element("su_thumbdown").type = ""; su_set_visible("su_separator2", true); su_set_visible("su_website_info_promo", true); su_set_visible("su_separator_promo", true); su_set_visible("su_referral_promo", true); su_set_visible("su_separator_category", true); su_set_visible("su_separator4", true); su_set_visible("su_video_promo", true); su_set_visible("su_separator6", true); su_set_visible("su_profile", true); su_set_visible("su_separator7", false); su_set_visible("su_mode", false); su_set_visible("su_stumble_menu", false); su_set_visible("su_category", false); su_set_visible("su_website_info", false); su_set_visible("su_network", false); // legacy network su_set_visible("su_messages", false); su_set_visible("su_field", false); su_has_searchbox = false; su_set_visible("su_filter", false); su_set_visible("su_aboutme", false); su_set_visible("su_matches", false); su_set_visible("su_groups", false); su_set_visible("su_myinfo", false); // su_set_visible("su_forum", false); // legacy forums su_set_visible("su_referral_menu", false); // su_set_visible("su_inbox-count", false); su_set_visible("su_referred", false); su_set_visible("su_page_feature_prompt", false); su_set_visible("firstrater", false); su_set_visible("su_stumble_topic", false); su_set_visible("su_stumble_topic_menu_left", false); su_set_visible("su_stumble_topic_menu_right", false); su_set_visible("su_sponsor", false); su_set_visible("su_tag", false); su_set_visible("su_tag2", false); su_set_visible("su_splitter_search_right", false); } else if (stumbleid == 0) { su_set_visible("su_start", true); su_set_visible("su_login", (! su_has_logged_in())); su_set_visible("su_stumble", false); su_set_visible("su_sites_promo", false); su_set_visible("su_friends", false); su_set_visible("su_thumbup", false); su_set_visible("su_thumbdown", false); su_get_element("su_thumbdown").type = ""; su_set_visible("su_separator2", false); su_set_visible("su_website_info_promo", false); su_set_visible("su_separator_promo", false); su_set_visible("su_referral_promo", false); su_set_visible("su_separator4", false); su_set_visible("su_separator_category", false); su_set_visible("su_video_promo", false); su_set_visible("su_separator6", false); su_set_visible("su_separator7", false); su_set_visible("su_profile", false); su_set_visible("su_mode", false); su_set_visible("su_stumble_menu", false); su_set_visible("su_category", false); su_set_visible("su_website_info", false); su_set_visible("su_network", false); // legacy network su_set_visible("su_messages", false); su_set_visible("su_field", false); su_has_searchbox = false; su_set_visible("su_filter", false); su_set_visible("su_aboutme", false); su_set_visible("su_matches", false); su_set_visible("su_groups", false); su_set_visible("su_myinfo", false); // su_set_visible("su_forum", false); // legacy forums su_set_visible("su_referral_menu", false); // su_set_visible("su_inbox-count", false); su_set_visible("su_referred", false); su_set_visible("su_page_feature_prompt", false); su_set_visible("firstrater", false); su_set_visible("su_stumble_topic", false); su_set_visible("su_stumble_topic_menu_left", false); su_set_visible("su_stumble_topic_menu_right", false); su_set_visible("su_sponsor", false); su_set_visible("su_tag", false); su_set_visible("su_tag2", false); su_set_visible("su_splitter_search_right", false); } else { // show rating buttons, menu, etc... su_set_visible("su_start", false); su_set_visible("su_login", false); su_set_visible("su_stumble", true); su_set_visible("su_separator4", ( (su_ds.getValue("$show_mode") && su_ds.getValue("$show_separators")) ) ); su_set_visible("su_separator_category", su_ds.getValue("$show_topics") || !su_get_element("su_stumble_topic_menu_left").collapsed); su_set_visible("su_thumbup", true); su_set_visible("su_thumbdown", true); su_get_element("su_thumbdown").type = "menu-button"; su_set_visible("su_separator2", su_ds.getValue("$show_separators")); su_set_visible("su_referral_promo", false); su_set_visible("su_separator_promo", false); su_set_visible("su_website_info_promo", false); su_set_visible("su_stumble_menu", true); su_set_visible("su_category", su_ds.getValue("$show_topics")); su_set_visible("su_website_info", su_ds.getValue("$show_info")); su_set_visible("su_field", su_ds.getValue("$show_field")); su_has_searchbox = su_ds.getValue("$show_field"); su_set_visible("su_splitter_search_right", su_ds.getValue("$show_field")); su_set_visible("su_tag", (su_ds.getValue("$show_tag") && su_ds.getValue("$show_field")) ); su_set_visible("su_tag2", (su_ds.getValue("$show_tag") && (! su_ds.getValue("$show_field"))) ); su_set_visible("su_referral_menu", su_ds.getValue("$show_referral")); su_set_visible("su_separator6", (! ( ( (! su_ds.getValue("$show_field")) && (! su_ds.getValue("$show_info")) && (! su_ds.getValue("$show_referral")) && (! su_ds.getValue("$show_tag")) ) || ( su_ds.getValue("$show_field") && (!su_ds.getValue("$show_tag")) ) || (! su_ds.getValue("$show_separators")) ) ) ); su_set_visible("su_aboutme", su_ds.getValue("$show_aboutme")); su_set_visible("su_sites_promo", false); su_set_visible("su_video_promo", false); su_set_visible("su_page_feature_prompt", false); su_set_visible("su_filter", su_ds.getValue("$show_filter")); su_set_visible("firstrater", false); su_set_visible("su_separator7", false); su_set_visible("su_stumble_topic", false); su_set_visible("su_stumble_topic_menu_left", false); su_set_visible("su_stumble_topic_menu_right", false); su_set_visible("su_sponsor", false); su_set_visible("su_profile", su_ds.getValue("$show_home")); su_set_visible("su_friends", su_ds.getValue("$show_friends")); su_set_inbox_status((su_ds.getValue("$newmessage")) ? '2' : ''); // su_set_visible("su_messages", su_ds.getValue("$show_messages")); su_set_visible("su_network", su_ds.getValue("$show_legacy_network")); su_set_visible("su_matches", su_ds.getValue("$show_matches")); // su_set_visible("su_forum", su_ds.getValue("$show_legacy_forums")); su_set_visible("su_groups", su_ds.getValue("$show_groups")); su_set_visible("su_myinfo", su_ds.getValue("$show_myinfo")); var mode_ids = [ "mode", // "mode_all", "mode_friends", "mode_news", "mode_photo", "mode_search", "mode_stumblers", "mode_video", "mode_wiki", "mode_more"]; var i; for (i = 0; i < mode_ids.length; i++) su_set_visible("su_" + mode_ids[i], su_ds.getValue("$show_" + mode_ids[i])); su_set_visible("su_mode_all", true); su_set_visible("su_recthumbup", su_ds.getValue("$dd_rec_rating") != 0); } } function su_refresh_dyn_channels() { su_invoke_global_event("dyn-channels-dirty", null); if (su_refreshing_dyn_channels) return; su_refreshing_dyn_channels = true; setTimeout( function (win) { win.su_invoke_global_event("update-dyn-channels", null); }, 500, window); } function su_update_dyn_channels() { su_refreshing_dyn_channels = false; if (! su_dyn_channels_dirty) return; if (su_mode_more_popup_open) return; su_dyn_channels_dirty = false; var channels = su_ds.getThruDomainChannels(true); if (! channels) { if (! su_ds.getValue("#checked_dyn_channels")) su_check_dyn_channels(); return; } var parent = su_get_element("su_mode"); var brother_el = su_get_element("su_mode_all"); var id; var channel_id; var el; var i; for (i = 0; i < channels.length; i++) { channel_id = su_get_channel_id(channels[i].domain); id = "su_mode_dyn_" + channel_id; el = su_get_element(id); if (el) el.parentNode.removeChild(el); id = "su_mode_more_" + channel_id; el = su_get_element(id); if (el) el.parentNode.removeChild(el); } var more_popup = su_get_element("su_mode_more_popup"); while (more_popup.lastChild) more_popup.removeChild(more_popup.lastChild); for (i = 0; i < channels.length; i++) { channel_id = su_get_channel_id(channels[i].domain); var icon_url = su_ds.getResourceURLFromName("favicons", channel_id + ".ico") id = "su_mode_more_" + channel_id; el = document.createElement("menuitem"); el.setAttribute("id", id); el.setAttribute("label", " " + channels[i].name); el.setAttribute("onclick", "su_handle_domain_mode_click(event, '" + channels[i].domain + "');"); el.setAttribute("tooltiptext", "StumbleThru " + channels[i].name); el.setAttribute("class", "menuitem-iconic"); el.setAttribute("image", icon_url); more_popup.appendChild(el); if (channels[i].show) { // If they've added a dyn channel button, we don't need to // educate via the info bubble. -- Jw su_ds.setValue("$shown_thru_domain_info_count", su_ds.getValue("~shown_thru_domain_info_count_max")); id = "su_mode_dyn_" + channel_id; el = document.createElement("toolbarbutton"); el.setAttribute("id", id); el.setAttribute("class", "su-hidetext"); el.setAttribute("su_ismode", "1"); el.setAttribute("onclick", "su_handle_domain_mode_click(event, '" + channels[i].domain + "');"); el.setAttribute("tooltiptext", "StumbleThru " + channels[i].name); el.setAttribute("image", icon_url); parent.insertBefore(el, brother_el); su_set_image(id, icon_url); } } su_refreshing_dyn_channels = false; su_update_thru_domain(su_get_browser_url(), null, null, null, true); su_reflow_toolbar(14); } // used by move_toolbar() to initialize splitters function su_init_splitters() { try { var sidebar_splitter = su_get_element("sidebar-splitter"); if (sidebar_splitter) { sidebar_splitter.addEventListener("DOMAttrModified", su_handle_sidebar_attr_modified, false); sidebar_splitter.addEventListener("mouseup", su_handle_sidebar_mouseup, false); } var width = su_ds.getValue("@search-width"); if (width == 0) { width = 156; su_ds.setValue("@search-width", width); } if (width > 400) { width = 400; su_ds.setValue("@search-width", width); } su_get_element("su_field").setAttribute("width", width + "px"); su_get_element("su_splitter_first_flexbox").collapsed = false; setTimeout(function (win) { win.su_refresh_splitters(true); }, 0, window); } catch (e) { su_log_error("INIT SPLITTERS", e, su_ds.getValue("@toolbar-position"), su_ds.getValue("@position-group")); } } // used during init to initialize globals and to survey existing // keybindings function su_init_keybinding_globals() { su_init_key_const_dictionaries(); var keys = document.getElementsByTagName("key"); for (var i = 0; i < keys.length; i++) su_keys_by_keyspec[su_get_keyspec_from_key(keys[i])] = keys[i]; } // used by init_keybinding_globals to populate // su_keyids_by_eventkeycode, su_chars_by_keyid and su_keyids_by_char function su_init_key_const_dictionaries() { var keyid; var property; for (property in KeyEvent) { if (su_is_property_garbage(KeyEvent, property)) continue; keyid = property.replace("DOM_",""); su_keyids_by_eventkeycode[KeyEvent[property]] = keyid; if (keyid.length == 4) su_chars_by_keyid[keyid] = String.fromCharCode(KeyEvent[property]); } su_keyids_by_eventkeycode[8] = "VK_BACK"; var o = su_chars_by_keyid; o["VK_SEMICOLON"] = ";"; o["VK_EQUALS]"] = "="; o["VK_MULTIPLY"] = "*"; o["VK_ADD"] = "+"; o["VK_SUBTRACT"] = "-"; o["VK_DECIMAL"] = "."; o["VK_DIVIDE"] = "/"; o["VK_COMMA"] = ","; o["VK_PERIOD"] = "."; o["VK_SLASH"] = "/"; // overwrites VK_DIVIDE in su_keyids_by_char o["VK_BACK_QUOTE"] = "`"; o["VK_OPEN_BRACKET"] = "["; o["VK_BACK_SLASH"] = "\\"; o["VK_CLOSE_BRACKET"] = "]"; o["VK_QUOTE"] = '"'; su_keyids_by_char = su_invert_dictionary(su_chars_by_keyid); } // used by init_keybinding_globals to get the keyspec from a key // element function su_get_keyspec_from_key(key) { var str = ""; var modifiers = key.getAttribute("modifiers").toLowerCase(); if (modifiers.indexOf("alt") != -1) str += "Alt+"; if (modifiers.indexOf("control") != -1) str += "Ctrl+"; if (modifiers.indexOf("meta") != -1) str += "Command+"; if (modifiers.indexOf("accel") != -1) { if (su_host.mac) str += "Command+"; else str += "Ctrl+" } if (modifiers.indexOf("shift") != -1) str += "Shift+"; var keyid; if (key.hasAttribute("key") && (key.getAttribute("key").length == 1)) { keyid = key.getAttribute("key").toUpperCase(); var keyid_tmp = su_keyids_by_char[keyid]; if (keyid_tmp) keyid = keyid_tmp; } else if (key.hasAttribute("keycode")) { keyid = key.getAttribute("keycode"); } if (! keyid) keyid = ""; str += keyid; return str; } // called by the global configure-toolbar event and during init // to update the key bindings function su_refresh_keybindings() { // It would be more friendly to other extensions if we'd add key // elements rather than attach a keyup listener to the window. // But we have to use a keyup listener in order to distinguish // between 'numeral keys on the number row' and 'numeral keys on // the numeric keypad w/ numlock turned on'. This is necessary to // avoid a conflict between binding Alt+VK_1 and typing a special // character via Alt+[keycode] using the numeric keypad on XP. // We're supposed to be able to distinguish between the number row // and the keypad keys using different keycodes (i.e. VK_1 vs // VK_NUMPAD1) [1], but if one of those keycodes is specified on a // key element, its command is never invoked (ref Firefox 1.5, XP). // -- JW // [1] // http://www.xulplanet.com/tutorials/xultu/keyshort.html var stumble_default; var reviews_default; var thumbup_default; var thumbdown_default; var tag_default; // var details_default; var toolbar_default; if (su_host.mac) { stumble_default = "Alt+VK_ESCAPE"; thumbup_default = "Alt+VK_F1"; thumbdown_default = "Alt+VK_F2"; tag_default = "ALT+VK_SLASH"; reviews_default = "Alt+VK_F3"; // details_default = "Alt+VK_F4"; toolbar_default = "Command+VK_F11"; } else if (su_host.win) { stumble_default = "Alt+VK_BACK_QUOTE"; thumbup_default = "Alt+VK_1"; thumbdown_default = "Alt+VK_2"; tag_default = "ALT+VK_SLASH"; reviews_default = "Alt+VK_3"; // details_default = "Alt+VK_4"; toolbar_default = "Ctrl+VK_F11"; } else { stumble_default = "Alt+VK_ESCAPE"; thumbup_default = "Alt+VK_F1"; thumbdown_default = "Alt+VK_F2"; tag_default = "ALT+VK_SLASH"; reviews_default = "Alt+VK_F3"; // details_default = "Alt+VK_F4"; toolbar_default = "Ctrl+VK_F11"; } var keyspecs = new Array(); su_commands_by_keyspec = new Object(); var keyspec; var rating_enabled = su_ds.getValue("$shortcuts_enabled"); keyspec = su_ds.getPrefValue("$shortcut_stumble", stumble_default); if (rating_enabled && (keyspec != "")) { keyspecs.push(keyspec); su_commands_by_keyspec[keyspec] = su_get_element("StumbleUpon:Stumble"); } keyspec = su_ds.getPrefValue("$shortcut_thumbup", thumbup_default); if (rating_enabled && (keyspec != "")) { keyspecs.push(keyspec); su_commands_by_keyspec[keyspec] = su_get_element("StumbleUpon:RateThumbup"); } keyspec = su_ds.getPrefValue("$shortcut_thumbdown", thumbdown_default); if (rating_enabled && (keyspec != "")) { keyspecs.push(keyspec); su_commands_by_keyspec[keyspec] = su_get_element("StumbleUpon:RateThumbdown"); } keyspec = su_ds.getPrefValue("$shortcut_tag", tag_default); if (rating_enabled && (keyspec != "")) { keyspecs.push(keyspec); su_commands_by_keyspec[keyspec] = su_get_element("StumbleUpon:Tag"); } keyspec = su_ds.getPrefValue("$shortcut_reviews", reviews_default); if (rating_enabled && (keyspec != "")) { keyspecs.push(keyspec); su_commands_by_keyspec[keyspec] = su_get_element("StumbleUpon:ViewReviews"); } // keyspec = su_ds.getPrefValue("$shortcut_details", details_default); // if (rating_enabled && (keyspec != "")) // { // keyspecs.push(keyspec); // su_commands_by_keyspec[keyspec] = su_get_element("StumbleUpon:RateThumbupDetailed"); // } keyspec = su_ds.getPrefValue("$shortcut_toolbar", toolbar_default); if (keyspec != "") { keyspecs.push(keyspec); su_commands_by_keyspec[keyspec] = su_get_element("StumbleUpon:ToggleToolbar"); } if (su_ds.getValue("$shortcut_toolbar") != toolbar_default) { var toggle_key = su_get_element("key_StumbleUpon:ToggleToolbar"); if (toggle_key.hasAttribute("command")) { toggle_key.setAttribute("savedcommand", toggle_key.getAttribute("command")); toggle_key.removeAttribute("command"); } } if (su_get_element("stumbleupon")) { var toolbar_keyspec = su_ds.getValue("$shortcut_toolbar"); if (toolbar_keyspec == "") { su_get_element("stumbleupon").setAttribute("toolbarname", "StumbleUpon Toolbar"); } else { su_get_element("stumbleupon").setAttribute("toolbarname", "StumbleUpon Toolbar (" + su_get_display_keyspec(su_ds.getValue("$shortcut_toolbar")) + ")"); } } for (keyspec in su_removed_keybindings_by_keyspec) { if (su_is_property_garbage(su_removed_keybindings_by_keyspec, keyspec)) continue; if (su_removed_keybindings_by_keyspec[keyspec]) { su_removed_keybindings_by_keyspec[keyspec].alive = false; } } for (var i = 0; i < keyspecs.length; i++) { var key; var binding; if (su_keys_by_keyspec[keyspecs[i]]) { key = su_keys_by_keyspec[keyspecs[i]]; binding = new Object(); binding.alive = true; binding.key = key; if (key.hasAttribute("command")) { binding.command = key.getAttribute("command"); key.removeAttribute("command"); } if (key.hasAttribute("oncommand")) { binding.oncommand = key.getAttribute("oncommand"); key.removeAttribute("oncommand"); } if (key.hasAttribute("onkeypress")) { binding.onkeypress = key.getAttribute("onkeypress"); key.removeAttribute("onkeypress"); } su_removed_keybindings_by_keyspec[keyspecs[i]] = binding; } } for (keyspec in su_removed_keybindings_by_keyspec) { if (su_is_property_garbage(su_removed_keybindings_by_keyspec, keyspec)) continue; if (su_removed_keybindings_by_keyspec[keyspec]) { var binding = su_removed_keybindings_by_keyspec[keyspec]; if (! binding.alive) { if (binding.command) binding.key.setAttribute("command", binding.command); if (binding.oncommand) binding.key.setAttribute("oncommand", binding.oncommand); if (binding.onkeypress) binding.key.setAttribute("onkeypress", binding.onkeypress); delete su_removed_keybindings_by_keyspec[keyspec]; } } } } // used by refresh_keybindings and the preferenceDialog to convert a // keyspec into its readable form function su_get_display_keyspec(keyspec) { var keyid = su_get_keyid_from_keyspec(keyspec); if (su_chars_by_keyid[keyid]) { var regexp = new RegExp(su_escape_regexp_chars(keyid) + "$"); keyspec = keyspec.replace(regexp, su_chars_by_keyid[keyid]); } return keyspec.replace("VK_", "").replace(/BACK$/, "BACKSPACE"); } // given a keyspec, returns a string that specifies the corresponding // modifiers for a key object function su_get_modifiers_from_keyspec(keyspec) { var parts = keyspec.split("+") var str = ""; for (var i = 0; i < parts.length; i++) { switch (parts[i]) { case "Alt": str += "alt "; break; case "Ctrl": str += "control "; break; case "Command": str += "meta "; break; case "Shift": str += "shift "; break; } } if (str != "") { str = str.substring(0, str.length); } return str; } // given a keyspec, returns the keyid portion function su_get_keyid_from_keyspec(keyspec) { var parts = keyspec.split("+"); if (parts[parts.length - 1] == "") return "+"; // probably cruft -- JW else return parts[parts.length - 1]; } function su_handle_content_click(event) { if (stumbleid == 0) return true; // getBrowser().selectedBrowser.su_content_clicked = true; try { if (su_is_server_page(event.target.href, "login.php?logout=1")) { setTimeout(su_handle_page_logout_click, 0); return su_cancel_event(event); } } catch (e) {} var ondblclick = ""; if (event.originalTarget.hasAttribute("ondblclick")) ondblclick = event.originalTarget.getAttribute("ondblclick"); var current_page = su_get_browser_url(event.target.ownerDocument, true); var slq = su_ds.globals.sluqh[current_page]; if (slq && (ondblclick == "")) ondblclick = "slr"; if (ondblclick == "") return true; var cancel_click = false; if (ondblclick == "stumble_thru") cancel_click = su_process_stumblethru_click(event); else if(ondblclick == "whitelist_stumbleupon_with_noscript") { var tld = su_get_tld(current_page); if (tld == su_servername) { su_update_noscript_whitelists(); cancel_click = true; var ps = su_get_service( "@mozilla.org/embedcomp/prompt-service;1", "nsIPromptService"); ps.alert(window, "StumbleUpon", "NoScript configuration updated. You may need to refresh the page or try the operation again."); } } else su_process_slstats_click(event, current_page, ondblclick, ((slq) ? slq : null)); if (cancel_click) return su_cancel_event(event); return true; } function su_process_stumblethru_click(event) { var target_anchor = su_get_target_anchor(event.originalTarget, 5); if (! target_anchor) return false; var target = target_anchor.getAttribute("href").toLowerCase(); if (target.indexOf("http://www." + su_servername + "/through.php?") != 0) return false; //!!! add stumblevideo case var through_match = target.match(/^http:\/\/[^\/]*\/through.php\?(.+)/); if (! through_match) return false; if (! through_match.length >= 2) return false; if (! su_ds.getValue("@toolbar-visible")) su_toggle_toolbar(); // parse out arguments var spliturl = through_match[1].split("&"); su_process_stumble_now(spliturl) } function su_process_stumble_now(args) { var topic_function = ""; var topic_displayed = ""; var mode = ""; var tag = ""; var user = ""; var topic = ""; for (var i = 0; i < args.length; i++) { var thearg = args[i]; var argsplit = thearg.split("="); if (argsplit.length > 1) { var key = decodeURIComponent(argsplit[0]); var value = decodeURIComponent(argsplit[1]); if (key == "mode") mode = value; else if (key == "tag") tag = value; else if (key == "user") user = value; else if (key == "topic") topic = value; } } if (mode == "") return false; // alert("MODE " + mode + " TAG " + tag + " USER " + user + " TOPIC " + topic); // we have something // news, all, tag, video, wiki, photo, language, incat su_unfocus_searchbox(); // put it in the box su_get_element("su_searchbox").value=tag; su_get_element("su_searchbox").removeAttribute("mode"); su_old_search = tag; su_last_typed_tag = 0; su_visited_searchbox = 1; var category; var label; // select and do it if (mode == "all") { category = 0; label = "All"; } else if (mode == "news") { //!!! tagged news? category = "news"; label = "News"; } else if (mode == "tag" && tag != "") { category = "TAG_" + tag; label = tag; } else if (mode == "user" && user != "" && tag == "") { category = user; label = user; } else if (mode == "user" && user != "" && tag != "") { //!!!!!???? category = "USERTAG_" + user + "_" + tag; label = user; } else if (mode == "subscriptions") { category = 'friends'; label = 'Stumblers'; } else if (mode == "incat" && topic != "") { category = topic; label = su_catnames[topic]; if(!label) { // Check for a tag as a backup when the topic id does not exist. if(tag) { category = "TAG_" + tag; label = tag; } else { su_set_location("http://www." + su_servername + "/tag/"); return true; } } } setTimeout(su_select_topic, 0, category, label, false); return true; } function su_process_slstats_click(event, current_page, ondblclick, slq) { var target_anchor = su_get_target_anchor(event.originalTarget, 5); if (! target_anchor) return; if ((! su_host.sha1) || (! su_ds.getValue("@enable_slstats"))) return; var sldetail = su_get_search_query_detail(null, current_page); su_ds.setValue("#sldetail", sldetail); sldetail.target = target_anchor.getAttribute("href"); var slt; if (target_anchor.hasAttribute("slt")) slt = target_anchor.getAttribute("slt"); else if (slq) slt = "" + slq + su_service.getSha1(target_anchor.getAttribute("href")); if (! slt) return; if (typeof(su_ds.globals.sltih[slt]) == "undefined") return; var row; var sli = su_ds.globals.sltih[slt]; var new_row; if (typeof(sli.rowid) != "undefined") { new_row = false; row = su_ds.selectRow("slclick", "_r", sli.rowid); } else if (sli.detail) { new_row = true; row = sli.detail; } else { new_row = true; row = new Object(); row.q = slq; row.i = sli.i; } switch (ondblclick) { case "slp": row.p = 1; break; case "sln": row.n = 1; break; case "slu": row.u = 1; break; case "slz": row.z = 1; break; case "slr": row.r = 1; break; } if (new_row) sli.rowid = su_ds.insertRow("slclick", row); else su_ds.updateRow(row); return; } function su_check_progress_listener() { // Check whether the datastore object has buffered any errors. setTimeout(function (win) { win.su_log_error(); }, 0, window); //!!! we have to keep doing this contantly because firefox likes to randomly // drop our addprogresslisteners. sad but true. // I think the progresslistener gets added to whichever browser // currently has focus in the tabbrowser. When a browser goes away, // our listener disappears. -- JW getBrowser().removeProgressListener(su_downloadProgressListener); getBrowser().addProgressListener(su_downloadProgressListener); // for instances where we still need a load listener ( such as interests_after.php ) // we can keep call this without removing it, that is part of the DOM spec window.addEventListener("DOMContentLoaded", su_on_load_page, true); } function su_add_progress_listener() { // We need this listener if we have tabs open getBrowser().addProgressListener(su_downloadProgressListener); } //************** END INITIALIZATION ****************/ //************** MODEL FUNCTIONS *******************/ function su_set_legacy_user_interests(str) { var blah3 = str.split("|"); var blah4 = blah3[1]; var blah5 = blah4.split(" "); su_user_interests = new Array(); for (var i = 0; i < blah5.length; i++) { if (blah5[i] != "") su_user_interests[blah5[i]] = 1; } } function su_set_user_interests(str) { var parts = str.split(" "); var i; su_user_interests = new Array(); for (i = 0; i < parts.length; i++) { if (parts[i] == "") continue; if (! parseInt(parts[i])) continue; su_user_interests[parts[i]] = 1; } } function su_store_user_interests() { var towrite = ""; var first = 0; for (var ii in su_user_interests) { if (su_is_property_garbage(su_user_interests, ii)) continue; if (first == 0) first = 1; else towrite += " "; towrite += ii + " "; } su_ds.setValue("$interests", towrite); su_ds.flushPrefs(); } function su_legacy_interests_after_page(doc) { var el = doc.getElementById("interests"); if (! el) return; su_set_legacy_user_interests(el.innerHTML); su_store_user_interests(); su_refresh_category_selector_batched(); clear_stumbles(); } function su_interests_page(doc) { var el = doc.getElementById("topic_list"); if (! el) return; su_process_topic_list(el.innerHTML); } function su_prefs_page(doc) { var el; el = doc.getElementById("changePassword"); if (! el) return; try { el.wrappedJSObject.addEventListener( "click", su_handle_change_password, false); } catch (e) {} } function su_tag_page(doc) { var el; el = doc.getElementById("thumbup"); if (el) { try { el.wrappedJSObject.addEventListener( "click", su_handle_interests_change_click, false); } catch (e) {} } el = doc.getElementById("thumbdown"); if (el) { try { el.wrappedJSObject.addEventListener( "click", su_handle_interests_change_click, false); } catch (e) {} } } function su_handle_interests_change_click() { setTimeout(su_get_interests, 1000); setTimeout(su_get_interests, 8000); } function su_portal_http_page(doc) { var el = doc.getElementById("topic_list"); if (! el) return; su_process_topic_list(el.innerHTML); } function su_process_topic_list(str) { if (str == su_ds.getValue("#prev_topic_list")) return; su_ds.setValue("#prev_topic_list", str); su_set_user_interests(str); su_store_user_interests(); su_refresh_category_selector_batched(); clear_stumbles(); } // // su_update_topic_list // // This is the same as su_process_topic_list, except it isn't restricted // to only running once per session with #prev_topic_list. To be honest, // I'm not sure why that is required, so I've created a new command so // topic updates can be driven by the web page via. the suLitebarApi. // function su_update_topic_list(str) { su_set_user_interests(str); su_store_user_interests(); su_refresh_category_selector_batched(); clear_stumbles(); } function su_process_friends_command(command_str) { if (command_str == su_ds.getValue("#prev_friends")) return; if (su_ds.getValue("#installing_all_avatars")) return; su_ds.setValue("#prev_friends", command_str); var friends = command_str.split(" "); friends.shift(); if(friends.length) { // If they have friends, then show the friends menu. if(!su_ds.getValue("$show_friends_user_changed")) { su_ds.setValue("$show_friends", true); su_set_visible("su_friends", true); } } var i; var contact; var mutuals = new Object(); var changed = false; var has_avatars = su_ds.getValue("$has_avatars"); if (! has_avatars) su_ds.setValue("#installing_all_avatars", true); var contacts = su_ds.selectAllRows("contact"); var new_contacts = new Array(); var contacts_by_id = new Object(); for (i = 0; i < contacts.length; i++) { if (contacts[i].contactid) contacts_by_id[contacts[i].contactid] = contacts[i]; } for (i = 0; i < friends.length; i++) { var nickname = friends[i].split(".")[0]; var contactid = friends[i].split(".")[1]; mutuals[contactid] = true; contact = null; if (contacts_by_id[contactid]) contact = contacts_by_id[contactid]; if (contact) { contacts_by_id[contact.contactid] = null; if (contact.contactid != contactid) { changed = true; contact.contactid = contactid; } if (contact.nickname != nickname) { changed = true; contact.nickname = nickname; } if (! contact.mutual) { changed = true; contact.mutual = 1; } if (changed) su_ds.updateRow(contact); if (! has_avatars) su_ds.refreshAvatar(contactid); contacts_by_id[contactid] = contact; } else { changed = true; contact = new Object(); contact.contactid = contactid; contact.nickname = nickname; contact.mutual = 1; su_ds.refreshAvatar(contactid); su_ds.insertRow("contact", contact); contacts_by_id[contactid] = contact; } } for (i = 0; i < contacts.length; i++) { if ((typeof (contacts[i])) == "undefined") { su_log_error("LEGACY FRIENDS"); contacts.splice(i, 1); i--; continue; } if ((typeof (contacts[i].contactid)) != "undefined") { if (! mutuals[contacts[i].contactid]) { if (contacts[i].mutual) { changed = true; contacts[i].mutual = 0; su_ds.updateRow(contacts[i]); } } } } if (changed) su_refresh_referral_menu(1); } /* function su_process_fbfriends_command(command_str) { var friends = command_str.split(" "); friends.shift(); var i; var contact; var contacts = su_ds.selectAllRows("contact"); var contacts_by_id = new Object(); var fbfriends = new Object(); for (i = 0; i < contacts.length; i++) { if (contacts[i].contactid) contacts_by_id[contacts[i].contactid] = contacts[i]; } for (i = 0; i < friends.length; i++) { var contactid = friends[i].split(".")[0]; var nickname = friends[i].split(".")[1]; var facebookid = friends[i].split(".")[2]; fbfriends[contactid] = true; contact = null; if (contacts_by_id[contactid]) contact = contacts_by_id[contactid]; if (contact) { contact.nickname = nickname; contact.fbid = facebookid; su_ds.updateRow(contact); } else { contact = new Object(); contact.contactid = contactid; contact.nickname = nickname; contact.fbid = facebookid; su_ds.insertRow("contact", contact); contacts_by_id[contactid] = contact; } } for (i = 0; i < contacts.length; i++) { if ((typeof (contacts[i].contactid)) != "undefined") { if (contacts[i].fbid && (! fbfriends[contacts[i].contactid])) contacts[i].fbid = 0; su_ds.updateRow(contacts[i]); } } } */ //************** END MODEL FUNCTIONS ***************/ //************** UTILITY FUNCTIONS *****************/ // See global.js for additional utility functions. function su_is_matching_domain(uri, domain, opt_parts_length_offset) { var splituri = uri.split("/"); if (splituri.length < 3) return false; var uri_domains = splituri[2].split("."); var ref_domains = domain.split("."); if ((typeof(opt_parts_length_offset) != "undefined") && (uri_domains.length - ref_domains.length) != opt_parts_length_offset) return false; else if (uri_domains.length < ref_domains.length) return false; var i = ref_domains.length-1; var j = uri_domains.length-1; while (i >= 0) { if (uri_domains[j] != ref_domains[i]) return false; i--; j--; } return true; } function su_get_domain(opt_url) { var url; if (opt_url) url = opt_url; else url = su_get_browser_url(); var url_parts = url.split("/"); if (url_parts.length < 3) return ""; return url_parts[2]; } function su_normalize_tag(str) { str = str.replace(/\s+/g, " "); str = str.replace(/\s*,+\s*/g, ", "); str = str.replace(/^,/, ""); str = str.replace(/,\s$/, ""); return str; } function su_is_sound(url) { // checks to see if url produces sound var last3 = url.substr(url.length-3).toLowerCase(); var last4 = url.substr(url.length-4).toLowerCase(); var last5 = url.substr(url.length-5).toLowerCase(); if ( last3 == ".qt" || last3 == ".ra" || last3 == ".rm" || last3 == ".rv" || last3 == ".au" || last3 == ".ul" || last4 == ".avi" || last4 == ".asf" || last4 == ".mpg" || last4 == ".wmf" || last4 == ".wmv" || last4 == ".wma" || last4 == ".wav" || last4 == ".mov" || last4 == ".mp3" || last4 == ".ram" || last4 == ".swf" || last4 == ".mp4" || last4 == ".mpe" || last4 == ".mpv" || last4 == ".mp2" || last4 == ".aac" || last4 == ".aif" || last4 == ".mid" || last4 == ".ogg" || last4 == ".ogm" || last4 == ".ac3" || last4 == ".fla" || last4 == ".awm" || last4 == ".ftk" || last4 == ".mod" || last4 == ".sid" || last4 == ".nap" || last4 == ".mmm" || last5 == ".aiff" || last5 == ".midi" || last5 == ".mpeg") { return 1; } else { return 0; } } function su_is_url_rateable(url, tld) { // Not enabled for about:, mailto:, etc. if (!url.match(/^(http|https|ftp):/i)) return false; // Not enabled for url pages if (url.indexOf(su_base_url + "url/") == 0 || url.indexOf(su_base_url + "url.php") == 0) return false; if (url == "http://video." + su_servername + "/") return false; if (tld) return true; return false; } function su_is_adult_category(cat) { if (cat == null) return false; cat += ""; switch (cat) { case "6": // Pornography case "159": // Fetish Sexuality case "193": // Hentai Anime case "510": // Gay Sex case "513": // Lesbian Sex case "521": // BDSM case "522": // Bisexual Sex case "531": // Transexual Sex return true; break; } return false; } function su_get_media_specs() { var specs = new Array(); var collection; var i; var doc = getBrowser().contentDocument; collection = doc.getElementsByTagName("EMBED"); for (i = 0; i < collection.length; i++) specs.push(su_get_media_spec(collection[i])); collection = doc.getElementsByTagName("OBJECT"); for (i = 0; i < collection.length; i++) specs.push(su_get_media_spec(collection[i])); collection = doc.getElementsByTagName("APPLET"); for (i = 0; i < collection.length; i++) specs.push(su_get_media_spec(collection[i])); collection = doc.getElementsByTagName("img"); for (i = 0; i < collection.length; i++) { var spec = su_get_media_spec(collection[i]); if (spec) specs.push(spec); } return specs; } function su_get_media_spec(el) { var spec = su_get_property_map(el); spec.tagName = el.tagName.toLowerCase(); if (el.boxObject) { spec.width = el.boxObject.width; spec.height = el.boxObject.height; spec.top = el.boxObject.top; } else { spec.width = 0; spec.height = 0; spec.top = 0; } if (spec.tagName == "img") { var area = spec.width * spec.height; if (area > 70000) return spec; else return null; } if (spec.type) return spec; if ((spec.tagName == "applet") || (spec.code && (spec.code.indexOf(".class") != -1))) spec.type = "application/x-java-applet"; else if ((spec.src && (spec.src.indexOf(".swf") != -1)) || (spec.movie && (spec.movie.indexOf(".swf") != -1))) spec.type = "application/x-shockwave-flash"; return spec; } function su_get_property_map(el) { var map = new Object(); var i; for (i = 0; i < el.attributes.length; i++) { // Add properties representing attributes. -- JW map[el.attributes.item(i).nodeName.toLowerCase()] = el.attributes.item(i).nodeValue; } var children = el.childNodes; for (i = 0; i < children.length; i++) { // Add properties representing param entities. -- JW if (children[i].tagName != "PARAM") continue; if (children[i].hasAttribute("name") && children[i].hasAttribute("value")) map[children[i].getAttribute("name").toLowerCase()] = children[i].getAttribute("value"); } return map; } function su_get_target_anchor(el, search_depth) { var found_el = null; var i; for (i = 0; i < search_depth; i++) { if (el.tagName && (el.tagName == "A")) { found_el = el; break; } if (el.parentNode) el = el.parentNode; else break; } return found_el; } function su_get_ancestor_by_prop_value(el, prop_name, prop_value, search_depth) { var found_el = null; var i; for (i = 0; i < search_depth; i++) { if (el.parentNode) el = el.parentNode; else break; if (el[prop_name] == prop_value) { found_el = el; break; } } return found_el; } function su_is_mutual_friend(nickname) { if (! nickname) return false; nickname += ""; if (nickname == "") return false; var query = nickname.toLowerCase(); var contacts = su_ds.selectAllRows("contact"); var found = false; var i; for (i = 0; i < contacts.length; i++) { if ((contacts[i].nickname) && (contacts[i].mutual) && (contacts[i].nickname.toLowerCase() == query)) { found = true; break; } } return found; } function su_prefix_article(str) { if (! str) return ""; if (str == "") return ""; var chr = str.charAt(0).toLowerCase(); var article; switch (chr) { case "a": case "e": case "i": case "o": case "u": article = "an"; break; default: article = "a"; break; } return article + " " + str; } function su_new_tab(event) { if (! event) return false; var platform_ctrl_key = (su_host.mac) ? event.metaKey : event.ctrlKey; var new_tab = false; if (event.button == 1 || (event.button == 0 && platform_ctrl_key)) new_tab = true; return new_tab; } function su_is_about_blank() { var doc = getBrowser().contentDocument; if(doc && (doc.location.toString() == "about:blank")) return true; else return false; } function su_cancel_event(event) { event.stopPropagation(); if (event.cancelable) event.preventDefault(); event.cancelBubble = true; return false; } // returns the number of browser windows function su_get_browser_window_count() { var enumerator = su_get_service( "@mozilla.org/appshell/window-mediator;1", "nsIWindowMediator") .getEnumerator("navigator:browser"); var count = 0; while (enumerator.hasMoreElements()) { count++; enumerator.getNext(); } return count; } function su_get_rdf_resource(resource_id) { return su_get_service( "@mozilla.org/rdf/rdf-service;1", "nsIRDFService") .GetResource(resource_id) .QueryInterface(Components.interfaces.nsIRDFResource) } function su_get_rdf_arc_literal(datasource, element, arc_id) { try { var arc = su_get_rdf_resource(arc_id); element.QueryInterface(Components.interfaces.nsIRDFResource); var target = datasource.GetTarget(element, arc ,true); if (target) return target.QueryInterface(Components.interfaces.nsIRDFLiteral).Value; } catch (e) {} return null; } function su_get_rdf_arc_int(datasource, element, arc_id) { try { var arc = su_get_rdf_resource(arc_id); element.QueryInterface(Components.interfaces.nsIRDFResource); var target = datasource.GetTarget(element, arc ,true); if (target) return target.QueryInterface(Components.interfaces.nsIRDFInt).Value; } catch (e) {} return null; } // returns a mime input stream, used primarily for wrapping POST data function su_get_mime_input_stream(str, content_type) { var data_stream = su_create_instance( "@mozilla.org/io/string-input-stream;1", "nsIStringInputStream"); data_stream.setData(str, str.length); var mime_stream = su_create_instance( "@mozilla.org/network/mime-input-stream;1", "nsIMIMEInputStream"); mime_stream.addHeader("Content-Type", content_type); mime_stream.addContentLength = true; mime_stream.setData(data_stream); return mime_stream.QueryInterface(Components.interfaces.nsIInputStream); } function su_get_browser_url(opt_doc, opt_raw) { var doc = (opt_doc) ? opt_doc : getBrowser().contentDocument; var url = doc.location.toString(); if (url.indexOf("chrome://ietab/content/reloaded.html?url=") == 0) url = url.substr(41); if (opt_raw) return url; if (su_is_matching_domain(url, "video." + su_servername)) { var detail = su_get_stumblevideo_detail(doc); if (detail) url = detail.url; } return url; } function su_get_browser_referrer_url(opt_doc, opt_raw) { var doc = (opt_doc) ? opt_doc : getBrowser().contentDocument; var url = doc.referrer.toString(); if (url.indexOf("chrome://ietab/content/reloaded.html?url=") == 0) url = url.substr(41); if (opt_raw) return url; // if (su_is_matching_domain(url, "video." + su_servername)) // { // var detail = su_get_stumblevideo_detail(doc); // if (detail) // url = detail.url; // } return url; } function su_dispatch_click(doc, id) { var el = doc.getElementById(id); if (! el) return; var evt = doc.createEvent("MouseEvent"); evt.initMouseEvent( "click", true, true, doc.defaultView, 1, 0, // screenX 0, // screenY 0, // clientX 0, // clientY false, false, false, false, 0, null); el.dispatchEvent(evt); } /* function su_dispatch_mouseover(doc, id) { var el = doc.getElementById(id); if (! el) return; var evt = doc.createEvent("MouseEvent"); evt.initMouseEvent( "mouseover", true, true, doc.defaultView, 1, 0, // screenX 0, // screenY 0, // clientX 0, // clientY false, false, false, false, 0, null); el.dispatchEvent(evt); } */ const su_DEBUG_ENABLED = true; /* function su_insert_before(parent, new_el, after_el) { if (parent && after_el && after_el.parentNode && (after_el.parentNode == parent)) after_el.insertBefore(new_el, after_el.nextSibling); else if (parent) parent.appendChild(new_el); } */ function su_get_element(id) { return document.getElementById(id); } // When doing a 'for ([prop] in [obj])', use this to verify that the // property isn't pollution from another extension. function su_is_property_garbage(obj, prop) { return ((typeof (obj[prop])) == "function"); } function su_invert_dictionary(dict) { var out = new Object(); var key; for (key in dict) { if (su_is_property_garbage(dict, key)) continue; out[dict[key]] = key; } return out; } function su_log_dd_uc(unseen) { if ( su_ds.lookup("userid:uc_logger_flag", stumbleid) || su_ds.getValue("@dd_uc")) { var str = " " + su_ds.getValue("@dd_uc_server") + " " + unseen + "\n"; su_ds.writeFile( su_ds.getLegacyNSIFile("stumbledd"), (su_ds.getTimestampStr(0) + str), true); su_ds.writeFile( su_ds.getLegacyNSIFile("stumbleddw"), (su_ds.getTimestampStr(1) + str), true); } } function su_get_time_s() { return Math.floor((new Date()).getTime() / 1000); } function su_trim(str) { return str.replace(/^\s*|\s*$/g,""); } function su_escape_regexp_chars(str) { return str.replace(/([\\\^\*\+\?\.\(\)\|\{\}\[\]])/g, "\\$1"); } function su_clone(obj) { return su_ds.deserialize(su_ds.serialize(obj, false)); } // append request param function su_arp(param_str, name, value, opt_get_flag) { var delimiter; if (opt_get_flag && (param_str.indexOf("&") == -1) && (param_str.indexOf("?") == -1)) delimiter = "?"; else delimiter = "&"; return param_str + ((param_str == "") ? "" : delimiter) + name + "=" + encodeURIComponent(value); } function su_build_request_param_string(spec) { var str = ""; var name; for (name in spec) { if (su_is_property_garbage(spec, name)) continue; str += ((str == "") ? "" : "&") + name + "=" + encodeURIComponent(spec[name]); } return str; } function su_create_instance(nsclass, nsinterface) { try { return Components.classes[nsclass] .createInstance(Components.interfaces[nsinterface]); } catch (e) { return null; } } function su_get_service(nsclass, nsinterface) { try { return Components.classes[nsclass] .getService(Components.interfaces[nsinterface]); } catch (e) { return null; } } // returns an nsIURI object for the specified uri function su_get_nsiuri(uri_str) { var uri = su_create_instance( "@mozilla.org/network/standard-url;1", "nsIURI"); uri.spec = uri_str; return uri; } // writes all arguments to a console message function su_dd() { if (! su_DEBUG_ENABLED) return; su_service.dd.apply(su_service, arguments); } function su_ddf() { su_service.ddf.apply(su_service, arguments); } window.su_log = su_dd; window.su_logf = su_ddf; // writes all properties of an object to a console message function su_dump_object(o) { var str = ""; var p; for (p in o) { try { str += "[" + p + "]\n" + o[p] + "\n\n"; } catch (e) { str += "[" + p + "] ERROR\n" + e + "\n\n"; } } su_log(str); } function su_log_error() { if (! su_DEBUG_ENABLED) return; su_service.logError.apply(su_service, arguments); } // send a notification to the event_observer for each window function su_invoke_global_event(event_id, detail, from) { if (event_id == "update-referral-menu") { su_ds.flushPrefs(); } else if ((event_id == "login") && detail && (! detail.skip_cookies) && detail.ignore_cookies) { su_process_cookies(true); detail.skip_cookies = true; } su_get_service( "@mozilla.org/observer-service;1", "nsIObserverService") .notifyObservers(null, "su_" + event_id, su_ds.serialize(detail)); } //************** END UTILITY FUNCTIONS ***************/ //******** FILE FUNCTIONS **********// // // Note: This code includes the ability to fallback to user prefs for file storage. // But since prefs are written frequently, useFailsafe should NOT be used except // when reading / writing very small files. // function _su_read_file_user(fname, useFailsafe) { // We fall back to using prefs if they have asked for it for this specific // operation, _and_ a previous file write operation failed _and_ the failsafe // option is enabled. // if(useFailsafe && su_ds.getValue("@userfile_write_failed") && su_ds.getValue("@enable_userfile_failsafe")) { // A previous write failed, so we are using prefs. var result = su_ds.getPrefValue("$file_" + fname + "_failsafe", ""); return result; } else { return su_ds.readFile(su_ds.getLegacyNSIFile(fname)); } } function _su_write_file_user(fname, data, useFailsafe) { if(useFailsafe && su_ds.getValue("@userfile_write_failed") && su_ds.getValue("@enable_userfile_failsafe")) { // If we have failed writing to the filesystem, then we failover // to using prefs for our user data storage. su_ds.setValue("$file_" + fname + "_failsafe", data); su_ds.flushPrefs(); } else { try { // Try the normal file operation. var file = su_ds.getLegacyNSIFile(fname); su_ds.writeFile(file, data); var result = su_ds.readFile(file); if(result != data) { // This is a ZoneAlarm ForceField hack. ForceField causes file writes to fail // silently, so we double-check whether the write succeeded and throw our own error // on failure. throw "Data is different"; } } catch(ex) { su_log_error("USERFILE FAILURE: " + ex); su_ds.setValue("$file_" + fname + "_failsafe", data); su_ds.setValue("@userfile_write_failed", true); su_ds.flushPrefs(); } } } function su_read_file_user(fname) { return _su_read_file_user(fname, fname == "stumbleurls"); } function su_write_file_user(fname, data) { _su_write_file_user(fname, data, fname == "stumbleurls"); } //***************** END FILE FUNCTIONS ******************// //***************** GUI HANDLERS ************************// // deals with interests if you select it from the menu item add more interests... function su_interests_pre() { su_interests(); su_set_mode_all(); } //!!! We probably ought to combine su_handle_mode_click and // su_select_topic, but to mitigate risk, this change is deferred // until after 3.0. -- JW function su_handle_mode_click(event, mode) { var new_tab = su_new_tab(event); var tag; switch (mode) { case "All": su_select_topic(0, mode, new_tab); break; case "Videos": su_select_topic("video", mode, new_tab); break; case "Photos": su_select_topic(302, mode, new_tab); break; case "Friends": su_select_topic("friends", mode, new_tab); break; case "Profiles": su_select_topic(44, mode, new_tab); break; case "Search": new_tab = new_tab || su_ds.getValue("$search_new_window"); setTimeout(su_show_search_dialog, 0, new_tab); break; case "News": su_select_topic("news", mode, new_tab); break; case "Wiki": su_select_topic("wiki", mode, new_tab); break; default: su_select_topic(mode, mode, new_tab); break; } } function su_handle_domain_mode_click(event, domain) { su_select_topic("TAG_" + domain, domain, su_new_tab(event)); } function su_select_topic(topic, label, new_tab, opt_force_stumble) { topic += ""; var lang = false; switch (topic) { case "0": su_set_mode(topic, label, "", "Stumble!", "Show next page"); break; case "44": su_set_mode(topic, label, "chrome://stumbleupon/content/skin/stumblers.png", "Stumble! ", "Stumble a profile"); break; case "302": su_set_mode(topic, label, "chrome://stumbleupon/content/skin/icon_tb_photo_hover.png", "Stumble! ", "Stumble a photo"); break; case "friends": su_set_mode(topic, label, "chrome://stumbleupon/content/skin/icon_tb_people.png", "Stumble! ", "Stumble a favorite"); break; case "video": su_set_mode(topic, label, "chrome://stumbleupon/content/skin/video.png", "Stumble! ", "Stumble a video"); break; case "news": su_set_mode(topic, label, "chrome://stumbleupon/content/skin/icon_tb_news.png", "Stumble! ", "Stumble a news item"); break; case "wiki": su_set_mode(topic, label, "chrome://stumbleupon/content/skin/wiki.png", "Stumble! ", "Stumble an article"); break; default: if (su_isInt(topic)) { su_set_mode(topic, label, "chrome://stumbleupon/content/skin/topic.png", "Stumble! ", "Stumble " + su_prefix_article(label) + " page"); } else if (topic.indexOf("LANG_") == 0) { lang = true; su_set_mode(topic, label, "chrome://stumbleupon/content/skin/topic.png", "Stumble! ", "Stumble " + su_prefix_article(label) + " page"); } else if (topic.indexOf("TAG_") == 0) { var tmp_topic = topic.substr(4).toLowerCase(); var favicon_url = null; if (su_ds.isThruDomain(tmp_topic)) { // If they've stumbled in a thru domain, we don't need to // educate via an info bubble. -- JW // su_ds.setValue("$shown_thru_domain_info_count", su_ds.getValue("~shown_thru_domain_info_count_max")); favicon_url = su_get_favicon_url(tmp_topic); } if (favicon_url) { su_set_mode(topic, label, favicon_url, "Stumble! ", "Stumble a page from " + label); } else { su_set_mode(topic, label, "chrome://stumbleupon/content/skin/search.png", "Stumble! ", "Stumble a '" + label + "' page"); } } else if (su_is_mutual_friend(topic)) { su_set_mode(topic, label, "chrome://stumbleupon/content/skin/mutual_favorites.png", "Stumble! ", "Stumble a favorite from " + label); } else { su_set_mode(topic, label, "chrome://stumbleupon/content/skin/stumbler_favorites.png", "Stumble! ", "Stumble a favorite from " + label); } break; } // if (! search) // { // su_get_element("su_searchbox").value = ""; // su_get_element("su_searchbox").removeAttribute("mode"); // su_old_search = ""; // su_last_typed_tag = 0; // su_visited_searchbox = 1; // } if (su_ds.getValue("$stumble_upon_change") || opt_force_stumble) stumble(new_tab); } function su_backup_places(error_label) { // Make a snapshot of bookmarks in the standard backup location, but // don't clobber an existing one. try { var datestr = (new Date).toLocaleFormat("%Y-%m-%d"); var name = PlacesUIUtils.getFormattedString("bookmarksBackupFilenameJSON", [datestr]); var nsifile = su_ds.getResourceNSIFile("temp", name); su_ds.deleteFile(nsifile); nsifile.create(Components.interfaces.nsIFile.NORMAL_FILE_TYPE, 0700); PlacesUtils.backupBookmarksToFile( nsifile, [PlacesUIUtils.leftPaneFolderId]); var target_dir = su_get_service( "@mozilla.org/file/directory_service;1", "nsIProperties") .get("ProfD", Components.interfaces.nsIFile); target_dir.append("bookmarkbackups"); if (! target_dir.exists()) target_dir.create(Components.interfaces.nsIFile.DIRECTORY_TYPE, 0700); var target_file; target_file = su_get_service( "@mozilla.org/file/directory_service;1", "nsIProperties") .get("ProfD", Components.interfaces.nsIFile); target_file.append("bookmarkbackups"); target_file.append(name); if (target_file.exists()) { var target_file2; target_file2 = su_get_service( "@mozilla.org/file/directory_service;1", "nsIProperties") .get("ProfD", Components.interfaces.nsIFile); target_file2.append("bookmarkbackups"); target_file2.append(name + ".su.saved.json"); if (! target_file2.exists()) target_file.copyTo(target_dir, name + ".su.saved.json"); su_ds.deleteFile(target_file); } if (! target_file.exists()) nsifile.copyTo(target_dir, name); } catch (e) { su_log_error(error_label, e); } } function su_handle_download_favs_command() { var detail = new Object(); detail.browser_label = su_host.label; window.openDialog( "chrome://stumbleupon/content/downloadFavsDialog.xul", "su_downloadFavsDialog", "chrome,dialog,centerscreen,dependent", detail); } function su_download_favs(start_download) { if (start_download) su_ds.setValue("$sync_bm_meta", true); var state = su_ds.getValue("$download_favs_state"); var context; var val; if (((state == "a") || (state == "c")) && (! start_download)) return; context = su_ds.getValue("$download_favs_detail"); if ((state == "a") || (state == "c") || (! context.mode)) { context = new Object(); context.begin_s = su_get_time_s(); context.end_s = 0; context.prekey = 0; context.prekey2 = 0; context.mode = 1; context.first = 1; context.download_target_count = 200; context.download_count = 0; context.apply_target_count = 200; context.apply_count = 0; context.count = 0; context.done = false; context.stopped = false; su_ds.setValue("$download_favs_detail", context); su_ds.setValue("#download_favs_detail", context); su_ds.setValue("$download_favs_state", "b"); su_ds.flushPrefs(); } else { su_ds.setValue("#download_favs_detail", context); } if (su_preference_dialog) { val = 5; el = su_preference_dialog.ownerDocument.getElementById("download_progress"); if (val != el.value) el.value = val; } su_set_download_favs_enabled(false); if (su_ds.getValue("#migrating_places")) return; setTimeout(function (win, context) { win.su_download_favs_getmetafavs(context) }, 0, window, context); } function su_download_favs_getmetafavs(context) { var params = ""; params = su_arp(params, "prekey", context.prekey); params = su_arp(params, "prekey2", context.prekey2); params = su_arp(params, "first", context.first); params = su_arp(params, "mode", context.mode); params = su_arp(params, "a", (su_ds.getValue("$sync_bm_adult") ? 1 : 0)) context.quiet = true; su_post_url_server_async( "getmetafavs.php", params, 15000, su_download_favs_getmetafavs_done, context); } function su_download_favs_getmetafavs_done(res) { try { if (res.status != 200) return; } catch (e) { return; } var context = res.detail; context.first = 0; su_ds.setValue("$download_favs_detail", context); su_ds.flushPrefs(); var s = ""; if (typeof(res.responseText) != "undefined") s = res.responseText; setTimeout(function (win, context, s) { win.su_download_favs_getmetafavs_done2(context, s); }, 0, window, context, s); } function su_download_favs_getmetafavs_done2(context, s) { if (context.stopped) return; // if (context.paused) // { // setTimeout(function (win, context, s) { // win.su_download_favs_getmetafavs_done2(context, s); }, // 1000, // window, // context, // s); // return; // } if (su_log_communication) su_log("response getmetafavs.php", s); var commands = s.split("\n"); window.setTimeout(function (win, context, commands) { win.su_download_favs2(context, commands); }, 0, window, context, commands); } function su_download_favs2(context, commands) { var command; var command_parts; if (su_ds.getValue("$download_favs_state") != "b") { // Download is done or stopped. su_process_command_queue(); } else if (commands.length) { command = commands.shift(); if (command.indexOf("META ") == 0) { context.download_count++; su_enqueue_command(16000, command); } else if (command.indexOf("BATCH ") == 0) { command_parts = command.split(" "); context.download_target_count = parseInt(command_parts[3]); context.apply_target_count = parseInt(command_parts[3]); su_ds.setValue("$download_favs_detail", context); su_ds.flushPrefs(); } else { su_process_command(command, context); } setTimeout(function (win, context, commands) { win.su_download_favs2(context, commands); }, 10, window, context, commands); } else if (! context.done) { setTimeout(function (win, context) { win.su_download_favs_getmetafavs(context); }, 0, window, context); su_process_command_queue(); } else if (context.done && (context.mode == 1)) { context.mode = 2; context.prekey = 0; context.done = false; setTimeout(function (win, context) { win.su_download_favs_getmetafavs(context); }, 0, window, context); su_process_command_queue(); } else if (context.done && (context.mode == 2)) { context.apply_target_count = context.download_count; context.apply_count = context.download_count - su_count_enqueued_commands(16000); su_ds.setValue("$download_favs_detail", context); su_ds.setValue("$download_favs_state", "c"); su_ds.flushPrefs(); su_ds.logEvent("dfth"); su_ds.setValue("#command_queue_context", null); su_process_command_queue(); } else { su_log_error("DOWNLOADFAVS TERMINATION", context, commands.length); } } function su_add_query_folder_bm(parent_folderid, target_folderids, tag, title, index) { var hs = su_ds.getHistoryService(); var query = hs.getNewQuery(); var bms = su_ds.getBookmarksService(); query.setFolders(target_folderids, target_folderids.length); query.searchTerms = tag; var opt = hs.getNewQueryOptions(); opt.sortingMode = opt.SORT_BY_LASTMODIFIED_DESCENDING; opt.resultType = opt.RESULTS_AS_URI; opt.queryType = 1; var query_str = hs.queriesToQueryString([query], 1, opt); var ios = su_get_service( "@mozilla.org/network/io-service;1", "nsIIOService"); var nsiuri = ios.newURI(query_str, null, null); return bms.insertBookmark( parent_folderid, nsiuri, index, title); } function su_get_favicon_url(domain) { if (! domain) return null; filename = su_get_channel_id(domain) + ".ico"; if (! su_ds.isResourceInstalled("favicons", filename)) return null; return su_ds.getResourceURLFromName("favicons", filename); } function su_get_channel_id(domain) { return domain.replace(/\./g, "_"); } function su_set_mode_all() { su_set_mode("0", "All", "", "Stumble!", "Show next page"); } function su_set_mode(cat, cat_label, src, label, tooltip) { cat += ""; var el; el = su_get_element("su_cat_langall"); if (el) el.hidden = (cat.indexOf("LANG_") != 0); el = su_get_element("su_cat_" + cat); if (el) su_get_element("su_category").selectedItem = el; su_selected_category = cat + ""; var tweakedCat = ''; if(cat_label) { tweakedCat = cat_label.replace(/\.com$/igm, ""); if(tweakedCat.length > 30) tweakedCat = tweakedCat.slice(0, 27) + "..."; } su_set_label("su_category", tweakedCat); if (! ((stumbleid == 0) && (! su_promo_mode))) { su_set_label("su_stumble", label); su_get_element("su_stumble").setAttribute("image2", src); su_get_element("su_stumble").setAttribute("tooltiptext", tooltip); } } function su_refresh_category_selector_batched() { // By delaying for 500 ms, we batch sets of closely spaced menu // updates. if (! su_refreshing_category_selector) { su_refreshing_category_selector = true; su_blocked_category_selector_refresh_pending = false; setTimeout( function (win) { win.su_invoke_global_event("refresh-category-selector", null); }, 500, window); } else if (su_refreshing_category_selector && (! su_blocked_category_selector_refresh_pending)) { // If refresh is blocked, push back the refresh event. su_blocked_category_selector_refresh_pending = true; setTimeout( function (win) { win.su_refresh_category_selector_batched(); }, 500, window); } } // This is the javascript way of creating an object and it's constructor: function su_CatObj(id, name) { this.id = id; this.name = name; } // Updates interest list in the in-cat stumble dialog, and saves current interests to disk (su_user_interests) function su_refresh_category_selector() { // we need to completely *remove* the menupopup and readd it // if we don't, the menupopup will be corrupt and it willl eventually // stop working. this is a firefox specific problem var incat = su_get_element("su_category"); // delete the menupopup and regenerate it var thechild; thechild = incat.childNodes[0]; if (typeof(thechild.hidePopup) == "function") { thechild.hidePopup(); su_unfocus(); } incat.removeChild(thechild); var ja = document.createElement("menupopup"); incat.appendChild(ja); su_load_categories(); // Now add new children var ints = new Array(); if (su_user_interests.length) { var cat2; for (cat2 in su_user_interests) { if (su_is_property_garbage(su_user_interests, cat2)) continue; if (su_is_property_garbage(su_catnames, cat2)) continue; if ((typeof(su_catnames[cat2])) == "undefined") continue; ints.push(new su_CatObj(cat2, su_catnames[cat2])); } } ints.sort(function (a, b) { if ( a.name < b.name ) return -1; if ( a.name > b.name ) return 1; return 0; }); // ** An individual stumbler ja = document.createElement("menuitem"); ja.setAttribute("class", "menuitem-iconic"); ja.setAttribute("label", "Pages from..."); ja.setAttribute("id", "su_cat_favorites_of2"); ja.setAttribute("tooltiptext", "Stumble someone's favorites"); ja.setAttribute("onclick", "su_favorites_of(event);"); ja.setAttribute("image", "chrome://stumbleupon/content/skin/stumbler_favorites.png"); ja.setAttribute("hidden", "true"); incat.childNodes[0].appendChild(ja); // ** stumble in "all" ja = document.createElement("menuitem"); ja.setAttribute("class", "menuitem-iconic"); // ja.setAttribute("label", su_ds.getValue("%menu.anytopic")); ja.setAttribute("label", "All"); ja.setAttribute("id", "su_cat_0"); ja.setAttribute("tooltiptext", "Stumble all"); ja.setAttribute("oncommand", "su_select_topic(0, 'All', false);"); ja.setAttribute("image", "chrome://stumbleupon/content/skin/all.png"); incat.childNodes[0].appendChild(ja); // ** Subscriptions ja = document.createElement("menuitem"); ja.setAttribute("class", "menuitem-iconic"); // ja.setAttribute("label", su_ds.getValue("%menu.anytopic")); ja.setAttribute("label", "Subscriptions"); ja.setAttribute("id", "su_cat_friends"); ja.setAttribute("tooltiptext", "Sites from people I've subscribed to"); ja.setAttribute("oncommand", "su_select_topic('friends', 'Subscriptions', false);"); ja.setAttribute("image", "chrome://stumbleupon/content/skin/icon_tb_people.png"); incat.childNodes[0].appendChild(ja); // ** StumbeThru ja = document.createElement("menuitem"); ja.setAttribute("class", "menuitem-iconic"); ja.setAttribute("label", "StumbleThru"); ja.setAttribute("id", "su_cat_stumblethru"); ja.setAttribute("tooltiptext", "StumbleThru a website"); ja.setAttribute("oncommand", 'su_set_server_location("stumblethru.php");'); ja.setAttribute("image", "chrome://stumbleupon/content/skin/domain.png"); incat.childNodes[0].appendChild(ja); // ** Search ja = document.createElement("menuitem"); ja.setAttribute("class", "menuitem-iconic"); ja.setAttribute("label", "Search"); ja.setAttribute("id", "su_cat_stumble_tags"); ja.setAttribute("tooltiptext", "Stumble within a query"); ja.setAttribute("oncommand", 'su_handle_mode_click(event, "Search");'); ja.setAttribute("image", "chrome://stumbleupon/content/skin/search.png"); incat.childNodes[0].appendChild(ja); // ** Photos ja = document.createElement("menuitem"); ja.setAttribute("class", "menuitem-iconic"); // ja.setAttribute("label", su_ds.getValue("%menu.anytopic")); ja.setAttribute("label", "Photos"); ja.setAttribute("id", "su_cat_photos"); ja.setAttribute("tooltiptext", "Stumble an image"); ja.setAttribute("oncommand", "su_select_topic(302, 'Photos', false);"); ja.setAttribute("image", "chrome://stumbleupon/content/skin/icon_tb_photo_hover.png"); incat.childNodes[0].appendChild(ja); // ** Videos ja = document.createElement("menuitem"); ja.setAttribute("class", "menuitem-iconic"); // ja.setAttribute("label", su_ds.getValue("@menu.anytopic")); ja.setAttribute("label", "Videos"); ja.setAttribute("id", "su_cat_video"); ja.setAttribute("tooltiptext", "Stumble a video"); ja.setAttribute("oncommand", "su_select_topic('video', 'Videos', false);"); ja.setAttribute("image", "chrome://stumbleupon/content/skin/video.png"); incat.childNodes[0].appendChild(ja); // ** News ja = document.createElement("menuitem"); ja.setAttribute("class", "menuitem-iconic"); // ja.setAttribute("label", su_ds.getValue("%menu.anytopic")); ja.setAttribute("label", "News"); ja.setAttribute("id", "su_cat_news"); ja.setAttribute("tooltiptext", "Stumble news"); ja.setAttribute("oncommand", "su_select_topic('news', 'News', false);"); ja.setAttribute("image", "chrome://stumbleupon/content/skin/icon_tb_news.png"); incat.childNodes[0].appendChild(ja); // ** contextual... // Create favorites of menu var random_topic_id = 499; var random_topic_name = 'StumbleUpon'; ja = document.createElement("menuitem"); ja.setAttribute("class", "menuitem-iconic"); ja.setAttribute("label", "More from " + random_topic_name); ja.setAttribute("tooltiptext", "More from " + random_topic_name); ja.setAttribute("id", "su_cat_morefrom"); ja.setAttribute("hidden", "true"); ja.setAttribute("oncommand", "su_select_topic(" + random_topic_id + ", '" + random_topic_name + "', false);"); ja.setAttribute("image", "chrome://stumbleupon/content/skin/topic.png"); incat.childNodes[0].appendChild(ja); var preTopicsItem = ja; var i; if (ints.length < 21) { for (i = 0; i < ints.length; i++) { var newname try { newname = ints[i].name.replace(/'/g, "\\\'"); } catch (e) { su_log_error("CAT NEWNAME", ints[i], i); continue; } ja = document.createElement("menuitem"); ja.setAttribute("label", ints[i].name); ja.setAttribute("id", "su_cat_" + ints[i].id); ja.setAttribute("tooltiptext", "Stumble " + ints[i].name); ja.setAttribute("oncommand", "su_select_topic(" + ints[i].id + ",'" + newname + "', false);"); incat.childNodes[0].appendChild(ja); } } else { var folders = new Array(); for (var cat in su_user_interests) { if (su_is_property_garbage(su_user_interests, cat)) continue; if (su_is_property_garbage(su_topicfolders, cat)) continue; if (su_is_property_garbage(su_catnames, cat)) continue; var folder = su_topicfolders[cat]; var name = su_catnames[cat]; if (typeof(folders[folder]) == "undefined") folders[folder] = new Array(); folders[folder][name]=cat; } for (i = 0; i < su_foldernames.length; i++) { var key = su_foldernames[i]; if (typeof(folders[key]) == "undefined") continue; // topics = folders[key]; ja = document.createElement("menu"); ja.setAttribute("label", key); ja.setAttribute("tooltiptext", "Stumble..."); var child = incat.childNodes[0].appendChild(ja); ja = document.createElement("menupopup"); var child2 = child.appendChild(ja); var newtopics = new Array(); var counter = 0; for (var catname in folders[key]) { if (su_is_property_garbage(folders[key], catname)) continue; newtopics[counter] = catname; counter++; } newtopics.sort(); for (var j = 0; j < newtopics.length; j++) { name = newtopics[j]; var catid = su_catids[name]; ja = document.createElement("menuitem"); ja.setAttribute("class", "topic-selector"); ja.setAttribute("label", name); ja.setAttribute("id", "su_cat_" + catid); ja.setAttribute("tooltiptext", "Stumble " + name); newname = name.replace(/'/g, "\\\'"); ja.setAttribute("oncommand", "su_select_topic(" + catid + ",'" + newname + "', false);"); child2.appendChild(ja); } } } if(preTopicsItem !== incat.childNodes[0].lastChild) { // If we have favorite topics, then include a separator before them ja = document.createElement("menuseparator"); incat.childNodes[0].insertBefore(ja, preTopicsItem.nextSibling); } ja = document.createElement("menuseparator"); incat.childNodes[0].appendChild(ja); ja = document.createElement("menuitem"); // ja.setAttribute("class", "topic-selector"); // ja.setAttribute("label", su_ds.getValue("%menu.addmoretopics")); ja.setAttribute("label", "Update Topics"); ja.setAttribute("tooltiptext", "Select different topics"); ja.setAttribute("id", "su_cat_addmore"); ja.setAttribute("oncommand", "su_interests_pre();"); incat.childNodes[0].appendChild(ja); // Create languages ja = document.createElement("menu"); // ja.setAttribute("class", "topic-selector"); ja.setAttribute("label", "Languages"); ja.setAttribute("tooltiptext", "Stumble pages in a specific language"); ja.setAttribute("id", "su_languages"); var langs2 = incat.childNodes[0].appendChild(ja); ja = document.createElement("menupopup"); // ja.setAttribute("class", "topic-selector"); ja.setAttribute("id", "su_languages-popup"); langs2.appendChild(ja); // first check to see if favorites of is already there var langs = su_get_element("su_languages-popup"); ja = document.createElement("menuitem"); ja.setAttribute("label", "All"); // ja.setAttribute("class", "topic-selector"); ja.setAttribute("id", "su_cat_langall"); ja.setAttribute("tooltiptext", "Stumble all"); ja.setAttribute("oncommand", "su_select_topic(0, 'All', false);"); langs.appendChild(ja); var languages = new Array(); languages['ZH'] = "Chinese"; languages['DA'] = "Danish"; languages['NL'] = "Dutch"; languages['FI'] = "Finnish"; languages['FR'] = "French"; languages['DE'] = "German"; languages['EL'] = "Greek"; languages['IT'] = "Italian"; languages['JA'] = "Japanese"; languages['PT'] = "Portuguese"; languages['ES'] = "Spanish"; languages['SV'] = "Swedish"; languages['TR'] = "Turkish"; for (var langid in languages) { if (su_is_property_garbage(languages, langid)) continue; var langname = languages[langid]; ja = document.createElement("menuitem"); ja.setAttribute("label", langname); // ja.setAttribute("class", "topic-selector"); ja.setAttribute("id", 'su_cat_LANG_' + langid); ja.setAttribute("tooltiptext", "Stumble " + langname + " pages"); ja.setAttribute("oncommand", "su_select_topic('" + 'LANG_' + langid + "', '" + langname + "', false);"); langs.appendChild(ja); } su_set_mode_all(); su_refreshing_category_selector = false; } function su_favorites_of(event) { su_unfocus_searchbox(); var stumbler = getBrowser().contentWindow.prompt("Enter the nickname of a stumbler:",""); // they clicked cancel if (stumbler && (stumbler != "")) { // select and do it su_select_topic(stumbler, stumbler, su_new_tab(event)); } else { su_set_mode_all(); } return true; } function su_unfocus_searchbox() { // unfocus search box so we don't end up searching when they hit enter if (su_get_element("su_searchbox").getAttribute("focused") == "true") su_unfocus(); } function su_unfocus() { if (! su_gui_initialized) return; if (document.commandDispatcher.focusedElement) { if ((document.commandDispatcher.focusedElement instanceof NSHTMLElement) || (document.commandDispatcher.focusedElement instanceof XULElement)) { document.commandDispatcher.focusedElement.blur(); } else { // non-HTML/XUL elements have no blur method; see bug 323805 document.commandDispatcher.focusedElement = null; } } } /* function su_tag_stumble() { su_unfocus_searchbox(); var tag = getBrowser().contentWindow.prompt("Please enter a tag",""); // they clicked cancel if (typeof(tag) == "undefined" || tag == "" || tag.length <= 0) { su_set_mode_all(); return false; } // put it in the box su_get_element("su_searchbox").value=tag; su_get_element("su_searchbox").removeAttribute("mode"); su_old_search = tag; su_last_typed_tag = 0; su_visited_searchbox = 1; // select and do it su_select_topic('TAG_' + tag, tag, false); return true; } */ function su_handle_referral_throbber_click(event) { su_stop_referred_throbber(); su_set_attribute("su_referred", "disabled", "true"); setTimeout(su_handle_referral_throbber_enable, su_ds.getValue("@click_throttle_ms")); su_select_topic(0, "All", su_new_tab(event), true); } function su_handle_referral_throbber_enable() { su_set_attribute("su_referred", "disabled", "false"); setTimeout(su_update_referred, 0); } /* function su_handle_report_dupe_command(url) { if (su_enable_freereporting) { var media = su_ds.serialize(su_get_media_specs()); var params = ""; params = su_arp(params, "url", stumbled_url); params = su_arp(params, "redirect", su_redirect_url); params = su_arp(params, "current", su_get_browser_url()); params = su_arp(params, "current_media", media); su_post_url_server_async( "dupe.php", params, 15000, su_generic_done); var ps = su_get_service( "@mozilla.org/embedcomp/prompt-service;1", "nsIPromptService"); ps.alert(window, "StumbleUpon", "Thanks for reporting this duplicate.\n\nIt will be reviewed by our support team."); } else { if (stumbled_url == "") { alert("You can't report pages that you haven't Stumbled upon."); } if (stumbleid == 0) return; var params = ""; params = su_arp(params, "url", stumbled_url); params = su_arp(params, "redirect", su_redirect_url); params = su_arp(params, "current", su_get_browser_url()); params = su_arp(params, "verified", 1); if (window.confirm("Are you sure that the following URL contains duplicate content?\n\n" + stumbled_url)) { su_post_url_server_async( "dupe.php", params, 15000, su_generic_done); } } } */ // Handler for menuitem "Report Miscat" function su_handle_report_miscat_command(tab_url) { if (su_enable_freereporting) { var url_detail = su_ds.lookup("url:url_detail", tab_url); var loc = "misclassified.php"; if (url_detail) { loc = su_arp(loc, "url", url_detail.url, true); loc = su_arp(loc, "redirect", url_detail.redirect_url, true); } else { loc = su_arp(loc, "url", tab_url, true); loc = su_arp(loc, "redirect", tab_url, true); } loc = su_arp(loc, "current", su_get_browser_url(), true); su_set_server_location(loc, null, true); } else { if (stumbled_url == "") { alert("You can't report pages that you haven't Stumbled upon."); return; } if (stumbleid == 0) return; var loc = "misclassified.php"; loc = su_arp(loc, "url", stumbled_url, true); loc = su_arp(loc, "redirect", su_redirect_url, true); loc = su_arp(loc, "current", su_get_browser_url(), true); loc = su_arp(loc, "verified", 1, true); if (window.confirm("Are you sure that the following URL is in the wrong topic?\n\n" + stumbled_url)) su_set_server_location(loc, null, true); } } // Handler for menuitem "Report Adult" function su_handle_report_adult_profile_command(tab_url) { if (su_enable_freereporting) { var nickname = su_get_profile_nickname(tab_url); var loc = "adult.php"; loc = su_arp(loc, "stumbler", nickname); su_set_server_location(loc, null, true); } else { if (stumbled_url == "") { alert("You can't report pages that you haven't Stumbled upon."); return; } if (stumbleid == 0) return; var url = su_get_browser_url(); var nickname = su_get_profile_nickname(url); var loc; if (nickname) { loc = "adult.php"; loc = su_arp(loc, "stumbler", nickname, true); loc = su_arp(loc, "verified", 1, true); } else { loc = "misclassified.php"; loc = su_arp(loc, "adult_content", 1, true); loc = su_arp(loc, "url", stumbled_url, true); loc = su_arp(loc, "redirect", su_redirect_url, true); loc = su_arp(loc, "current", url, true); loc = su_arp(loc, "verified", 1, true); } if (window.confirm("Are you sure that the following URL contains adult content?\n\n" + stumbled_url)) su_set_server_location(loc, null, true); } } function su_handle_report_wrong_language_command(tab_url) { if (su_enable_freereporting) { var url_detail = su_ds.lookup("url:url_detail", tab_url); var loc = "wrong_language.php"; if (url_detail) { loc = su_arp(loc, "url", url_detail.url, true); loc = su_arp(loc, "redirect", url_detail.redirect_url, true); } else { loc = su_arp(loc, "url", tab_url, true); loc = su_arp(loc, "redirect", tab_url, true); } loc = su_arp(loc, "current", su_get_browser_url(), true); su_set_server_location(loc, null, true); } else { if (stumbled_url == "") { alert("You can't report pages that you haven't Stumbled upon."); return; } if (stumbleid == 0) return; var loc = "wrong_language.php"; loc = su_arp(loc, "url", stumbled_url, true); loc = su_arp(loc, "redirect", su_redirect_url, true); loc = su_arp(loc, "current", su_get_browser_url(), true); loc = su_arp(loc, "verified", 1, true); if (window.confirm("Are you sure that the following URL is in the wrong language?\n\n" + stumbled_url)) su_set_server_location(loc, null, true); } } // Handler for menuitem "Report Spam" function su_handle_report_spam_command(tab_url) { if (su_enable_freereporting) { var url_detail = su_ds.lookup("url:url_detail", tab_url); var loc = "spam.php"; if (url_detail) { loc = su_arp(loc, "url", url_detail.url, true); loc = su_arp(loc, "redirect", url_detail.redirect_url, true); } else { loc = su_arp(loc, "url", tab_url, true); loc = su_arp(loc, "redirect", tab_url, true); } loc = su_arp(loc, "current", su_get_browser_url(), true); su_set_server_location(loc, null, true); // ps.alert(window, "StumbleUpon", "Thanks for helping improve stumble selection."); } else { if (stumbled_url == "") { alert("You can't report pages that you haven't Stumbled upon."); return; } if (stumbleid == 0) return; var loc = "spam.php"; loc = su_arp(loc, "url", stumbled_url, true); loc = su_arp(loc, "redirect", su_redirect_url, true); loc = su_arp(loc, "current", su_get_browser_url(), true); loc = su_arp(loc, "verified", 1, true); if (window.confirm("Are you sure that the following URL is spam?\n\n" + stumbled_url)) su_set_server_location(loc, null, true); } } function su_handle_report_badware_command(tab_url) { if (su_enable_freereporting) { var url_detail = su_ds.lookup("url:url_detail", tab_url); var params = ""; if (url_detail) { loc = su_arp(loc, "url", url_detail.url, true); loc = su_arp(loc, "redirect", url_detail.redirect_url, true); } else { loc = su_arp(loc, "url", tab_url, true); loc = su_arp(loc, "redirect", tab_url, true); } params = su_arp(params, "current", su_get_browser_url()); su_post_url_server_async( "badware.php", params, 15000, function (){}); var ps = su_get_service( "@mozilla.org/embedcomp/prompt-service;1", "nsIPromptService"); ps.alert(window, "StumbleUpon", "Thanks for reporting this stumble.\n\nIt will be reviewed by our support team."); } else { if (stumbled_url == "") { alert("You can't report pages that you haven't Stumbled upon."); } if (stumbleid == 0) return; var params = ""; params = su_arp(params, "url", stumbled_url); params = su_arp(params, "redirect", su_redirect_url); params = su_arp(params, "current", su_get_browser_url()); params = su_arp(params, "verified", 1); if (window.confirm("Are you sure that the following URL contains hostile content?\n\n" + stumbled_url)) { su_post_url_server_async( "badware.php", params, 15000, su_generic_done); } } } // Handler for menuitem "Report 404" function su_handle_report_404_command(tab_url) { //!!! we shouldn't really report 404, it should be something else (user 404?) if (su_enable_freereporting) { var url_detail = su_ds.lookup("url:url_detail", tab_url); var params = ""; if (url_detail) { params = su_arp(params, "url", url_detail.url); params = su_arp(params, "redirect", url_detail.redirect_url); } else { params = su_arp(params, "url", tab_url); params = su_arp(params, "redirect", tab_url); } params = su_arp(params, "current", su_get_browser_url()); params = su_arp(params, "status", 404); su_post_url_server_async( "404.php", params, 15000, su_generic_done); var ps = su_get_service( "@mozilla.org/embedcomp/prompt-service;1", "nsIPromptService"); ps.alert(window, "StumbleUpon", "Thanks for reporting this broken page.\n\nIt will be reviewed by our support team."); } else { if (stumbled_url == "") { alert("You can't report pages that you haven't Stumbled upon."); } if (stumbleid == 0) return; var params = ""; params = su_arp(params, "url", stumbled_url); params = su_arp(params, "redirect", su_redirect_url); params = su_arp(params, "current", su_get_browser_url()); params = su_arp(params, "status", 404); params = su_arp(params, "verified", 1); if (window.confirm("Are you sure that the following URL is 404 or broken?\n\n" + stumbled_url)) { su_post_url_server_async( "404.php", params, 15000, su_generic_done); //alert("404 reported for page:\n\n" + stumbled_url); } } } function su_handle_report_inaccurate_command(tab_url) { if (su_enable_freereporting) { var url_detail = su_ds.lookup("url:url_detail", tab_url); var params = ""; if (url_detail) { params = su_arp(params, "url", url_detail.url); params = su_arp(params, "redirect", url_detail.redirect_url); } else { params = su_arp(params, "url", tab_url); params = su_arp(params, "redirect", tab_url); } params = su_arp(params, "current", su_get_browser_url()); su_post_url_server_async( "inaccurate.php", params, 15000, su_generic_done); var ps = su_get_service( "@mozilla.org/embedcomp/prompt-service;1", "nsIPromptService"); ps.alert(window, "StumbleUpon", "Thanks for helping improve stumble selection."); } else { if (stumbled_url == "") { alert("You can't report pages that you haven't Stumbled upon."); } if (stumbleid == 0) return; var params = ""; params = su_arp(params, "url", stumbled_url); params = su_arp(params, "redirect", su_redirect_url); params = su_arp(params, "current", su_get_browser_url()); params = su_arp(params, "verified", 1); if (window.confirm("Are you sure that the following URL contains inaccurate information?\n\n" + stumbled_url)) { su_post_url_server_async( "inaccurate.php", params, 15000, su_generic_done); } } } function su_handle_filter_command(tmp_adult) { var params = ""; params = su_arp(params, "sadult", tmp_adult); su_post_url_server_async( "setoption.php", params, 15000, su_generic_done); } // Handler for menuitem "Change Current User" and used by newuserWindow function su_show_signin_dialog() { su_unfocus_searchbox(); var detail = new Object(); detail.userid = ""; detail.password = ""; detail.nickname = ""; detail.enableg = 0; detail.enableu = 0; detail.disableu = 0; detail.disableg = 0; detail.autologout = false; window.openDialog( "chrome://stumbleupon/content/signinDialog.xul", "su_sign_in", "chrome,modal,dialog,centerscreen,dependent", detail); } function su_get_autologout_for_user(str) { var pref = "stumble." + str + ".autologout"; if (su_ds.isPrefDefined(pref)) { // easy, uncommon case where str is the userid return su_ds.getValue(pref); } // more common case where str is the nickname var ids = su_ds.getValue("@id_list").split(":"); var i; for (i = 0; i < ids.length; i++) { if (ids[i] == "") continue; if (su_ds.isPrefDefined("stumble." + ids[i] + ".nick") && (str == su_ds.getValue("stumble." + ids[i] + ".nick"))) { return su_ds.getPrefValue("stumble." + ids[i] + ".autologout", false); } } return false; } function su_handle_signin_dialog_accept(detail) { if (stumbleid != 0) su_ds.deleteStoredPassword(); stumbleid = detail.userid; su_ds.setValue("@current_user", detail.userid); var new_profile = (! su_ds.isPrefDefined("$nick")); var unhashed_password = detail.password; var password = null; if (su_enable_hashed_password) password = su_ds.getEncodedPassword(unhashed_password, detail.userid); su_ds.storePassword(password, unhashed_password); su_ds.setValue("$autologout", detail.autologout); su_ds.setValue("$nick", detail.nickname); if(detail.thumbup_count) { su_ds.setValue("$thumbup_count", detail.thumbup_count); su_thumbup_count_changed(); } if(detail.stumble_count) { su_ds.setValue("$stumble_count", detail.stumble_count); su_stumble_count_changed(); } su_enable_client_features(detail.enableg); su_enable_user_features(detail.enableu); su_disable_client_features(detail.disableg); su_disable_user_features(detail.disableu); // now sync this stuff before we crash su_ds.flushPrefs(); var login_detail = new Object(); login_detail.skip_cookies = false; login_detail.ignore_cookies = true; login_detail.new_profile = new_profile; login_detail.new_user_prompt = false; su_invoke_global_event("login", login_detail); var loc = "discover/activity"; su_set_server_location(loc, null, !su_is_about_blank()); } // Handler for menuitem "Change Password" function su_handle_change_password() { su_unfocus_searchbox(); var detail = new Object(); detail.password = ""; detail.id = stumbleid; window.openDialog( "chrome://stumbleupon/content/passwordDialog.xul", "su_password", "chrome,modal,dialog,centerscreen,dependent", detail); } function su_handle_password_dialog_accept(detail) { // change local password var unhashed_password = detail.password; var password = null; if (su_enable_hashed_password) password = su_ds.getEncodedPassword(unhashed_password, stumbleid); su_ds.storePassword(password, unhashed_password); var cookieManager = su_get_service( "@mozilla.org/cookiemanager;1", "nsICookieManager"); cookieManager.remove("." + su_servername, "PHPSESSID", "/", 0); su_invoke_global_event("change-password", null); alert("Password changed"); } // Handler for menuitem "Feedback" function su_feedback() { if (stumbleid == 0) return false; // Redirect to the feedback page getBrowser().contentDocument.location = su_base_url + "feedback.php"; return true; } // Handler for menuitem "Sign-out" function su_handle_logout(logout_from_website) { var doc = getBrowser().contentDocument; if (stumbleid == 0) return false; var detail = new Object(); detail.response = 0; window.openDialog( "chrome://stumbleupon/content/signoutDialog.xul", "su_sign_out", "chrome,modal,dialog,centerscreen,dependent", detail); if (detail.response == 1) //if (window.confirm("Are you *sure* you would like to Sign-out?\n\n(Click CANCEL if you do not know your password,\nor you will LOSE THIS ACCOUNT)")) { su_invoke_global_event("logout", null) if (logout_from_website) su_set_location("http://www." + su_servername + "/login.php?logout=1", null, null, null); else { var url = doc.location.toString(); if (su_is_matching_domain(url, su_servername)) { su_set_location(url); } } } return true; } // handles the global login event function su_login(skip_cookies, ignore_cookies, new_profile, new_user_prompt) { if (su_stumble_async_context && su_stumble_async_context._request) { // kill the pending action su_service.abortPostAsync(su_stumble_async_context._request); } su_init_login(skip_cookies, ignore_cookies); // clears user session globals su_load_data1(new_profile); if (! new_user_prompt) su_ds.setValue("$intro_count", 15); if (! su_ds.getValue("~visited_signup")) su_show_searchlinks_dialog(new_user_prompt, false, false); su_load_data2(true); // calls su_configure_toolbar() su_ds.setValue("~visited_signup", false); } // handles the global change-password event function su_change_password() { stumblepass = su_ds.getStoredPassword(); } function su_has_logged_in() { var ids = su_ds.getValue("@id_list").split(":"); var found = false; var i; for (i = 0; i < ids.length; i++) { if (ids[i] == "") continue; found = true; break; } return found; } // handles the global configure-toolbar event and is used by // load_data2() function su_configure_toolbar(from_preference_dialog) { if (! from_preference_dialog) { try { su_close_info(); } catch (e) { su_log_error("CONFIGURE CLOSEINFO", e, from_preference_dialog); } try { su_move_toolbar(true, 1); } catch (e) { su_log_error("CONFIGURE MOVE", e, from_preference_dialog, su_ds.getValue("@toolbar-position"), su_ds.getValue("@position-group")); } try { su_refresh_toggle_button(true); } catch (e) { su_log_error("CONFIGURE TOGGLE", e, from_preference_dialog); } } try { su_set_mode_all(); } catch (e) { su_log_error("CONFIGURE SET MODE", e, from_preference_dialog); } try { su_init_labels(); } catch (e) { su_log_error("CONFIGURE LABELS", e, from_preference_dialog); } try { if (su_host.mac) su_set_attribute("su_thumbdown", "mac", "true"); } catch (e) { su_log_error("CONFIGURE THUMBDOWN", e, from_preference_dialog); } try { su_init_toolbar_element_visibility(); } catch (e) { su_log_error("CONFIGURE HIDDEN STATES", e, from_preference_dialog); } if (stumbleid != 0) { try { su_set_autocomplete_type(su_ds.getValue("$autocomplete_type")); } catch (e) { su_log_error("CONFIGURE AUTOCOMPLETE", e, from_preference_dialog); } try { su_dyn_channels_dirty = true; su_update_dyn_channels(); } catch (e) { su_log_error("CONFIGURE DYN CHANNEL BUTTONS", e, from_preference_dialog); } try { su_refresh_category_selector(); } catch (e) { su_log_error("CONFIGURE CATEGORY SELECTOR", e, from_preference_dialog); } try { su_referral_menu_dirty = true; su_update_referral_menu(); } catch (e) { su_log_error("CONFIGURE REFERRAL MENU", e, from_preference_dialog); } try { su_refresh_keybindings(); } catch (e) { su_log_error("CONFIGURE KEYBINDINGS", e, from_preference_dialog); } } su_reflow_toolbar("CONFIGURE"); setTimeout(function (win, url) { win.su_refresh_pagemeta(false, 2); }, 0, window); setTimeout(function (win) { win.su_reflow_toolbar("CONFIGURE2"); }, 500, window); setTimeout(function (win) { win.su_reflow_toolbar("CONFIGURE3"); }, 2000, window); } function su_verify_bookmarks_folder() { if (! su_host.places) return; var bms = su_ds.getBookmarksService(); var folderid = su_ds.getValue("$bm_folderid"); var tmpidx; if (folderid != 0) { tmpidx = -1; try { tmpidx = bms.getItemIndex(folderid); } catch (e) {} if (tmpidx != -1) return; } var children = Application.bookmarks.menu.children; var i; var folders_by_label = new Object(); var nonfolders_by_label = new Object(); var item; for (i = 0; i < children.length; i++) { item = children[i]; if ((typeof item.title) != "string") continue; if (item.title.indexOf("StumbleUpon") == 0) { if (item.type == "folder") folders_by_label[item.title] = item; else nonfolders_by_label[item.title] = item; } } item = null; if ((! folders_by_label["StumbleUpon"]) && (! nonfolders_by_label["StumbleUpon"])) { item = Application.bookmarks.menu.addFolder("StumbleUpon"); } var basename = "StumbleUpon - " + su_ds.getValue("$nick"); var i = 1; var candidate_name; while (! item) { if (i == 1) candidate_name = basename; else candidate_name = basename + " (" + i + ")"; if (folders_by_label[candidate_name]) item = folders_by_label[candidate_name]; else if (! nonfolders_by_label[candidate_name]) item = Application.bookmarks.menu.addFolder(candidate_name); i++; } su_ds.setValue("$bm_folderid", item.id); su_ds.flushPrefs(); } // handles the global logout event function su_logout() { // 0. If we don't hide the popup, the menu get munged var stumble_popup = su_get_element("su_stumble_popup"); if (typeof(stumble_popup.hidePopup) == "function") { stumble_popup.hidePopup(); su_unfocus(); } if (su_stumble_async_context && su_stumble_async_context._request) { // kill the pending action su_service.abortPostAsync(su_stumble_async_context._request); } su_stumbleReporter.stop(); try { su_prefetcher.stop(); su_prefetcher.clearTargets(); } catch (e) { su_log_error("PREFETCHER 4", e); } try { su_close_all_messages(); } catch (e) { su_log_error("LOGOUT CLOSEALLMSGS", e); } su_logout_auth(); // clears user session globals su_init_labels(); su_init_toolbar_element_visibility(); su_refresh_pagemeta(false, 5); su_get_element("su_stumble").setAttribute("image2", ""); setTimeout(su_reflow_toolbar, 0, 2); su_commands_by_keyspec = new Object(); window.removeEventListener("keyup", su_handle_window_keyup, false); window.removeEventListener("keypress", su_handle_window_keypress, false); var toggle_key = su_get_element("key_StumbleUpon:ToggleToolbar"); if (toggle_key) toggle_key.setAttribute("command", toggle_key.getAttribute("savedcommand")); var toolbar_el = su_get_element("stumbleupon"); if (toolbar_el) toolbar_el.setAttribute("toolbarname", toolbar_el.getAttribute("savedtoolbarname")); } // handles the Extension Manager uninstall event in Firefox 1.5+; // prompts for uninstallation options function su_handle_em_uninstall() { su_uninstall_scheduled = true; var recent_window = su_get_service( "@mozilla.org/appshell/window-mediator;1", "nsIWindowMediator") .getMostRecentWindow("navigator:browser"); if (window != recent_window) return; var detail = new Object(); detail.logout = false; detail.remove_data = false; detail.delete_account = false; su_unfocus_searchbox(); window.openDialog( "chrome://stumbleupon/content/uninstallDialog.xul", "su_uninstall_options", "chrome,modal,dialog,centerscreen,dependent", detail); if (detail.delete_account) { if (su_enable_hashed_password) { su_post_url_server( "delete_account.php", "version=" + su_verstring + "&stumbler=" + stumbleid + "&password=" + stumblepass); } else { su_post_url_server( "delete_account.php", "version=" + su_verstring + "&stumbler=" + stumbleid + "&password=" + encodeURIComponent(stumblepass)); } } if (detail.logout) su_invoke_global_event("logout", null); if (detail.remove_data) su_invoke_global_event("schedule-remove-data", null); } // handles the global schedule-remove-data event function su_schedule_remove_data() { // We remove the data now for good measure, then we remove it again // when each window is closed and when the app quits. -- JW su_remove_data_scheduled = true; su_remove_data(); } // removes all stumbleupon files and preferences function su_remove_data() { var ids = new Array(); try { ids = su_ds.getValue("@id_list").split(":"); } catch (e) {} var i; for (i = 0; i < ids.length; i++) { if (ids[i] == "") continue; su_ds.deleteFile(su_ds.getLegacyNSIFile("stumbleurls", ids[i])); su_ds.deleteFile(su_ds.getLegacyNSIFile("stumblerating", ids[i])); su_ds.deleteFile(su_ds.getLegacyNSIFile("stumbletags", ids[i])); su_ds.deleteFile(su_ds.getLegacyNSIFile("stumblequeries", ids[i])); } var file = su_get_service( "@mozilla.org/file/directory_service;1", "nsIProperties") .get("ProfD", Components.interfaces.nsIFile); file.append("StumbleUpon"); su_ds.deleteDirectory(file); var pref_names = su_ds.getPrefNames("stumble."); for (i = 0; i < pref_names.length; i++) { try { su_ds.clearPref(pref_names[i]); } catch (e) {} } var cookieManager = su_get_service( "@mozilla.org/cookiemanager;1", "nsICookieManager"); cookieManager.remove("." + su_servername, "PHPSESSID", "/", 0); cookieManager.remove("." + su_servername, "stumble_user", "/", 0); cookieManager.remove("." + su_servername, "stumble_pass", "/", 0); cookieManager.remove("." + su_servername, "tsuu", "/", 0); cookieManager.remove("." + su_servername, "tsut", "/", 0); cookieManager.remove("." + su_servername, "nickname", "/", 0); cookieManager.remove("." + su_servername, "searchlinks", "/", 0); cookieManager.remove("." + su_servername, "thru_domains", "/", 0); cookieManager.remove("." + su_servername, "enableu", "/", 0); cookieManager.remove("." + su_servername, "enableg", "/", 0); cookieManager.remove("." + su_servername, "SU_REMEMBER", "/", 0); su_logout_server(); } // Handler for menuitem "Chatroom" function su_chat() { var doc = getBrowser().contentDocument; if (stumbleid == 0) return; // Redirect to the chat page getBrowser().contentDocument.location = su_base_url + "chat.php"; } // Handler for button "FirstRater" (the happy face) function firstrater_func(event) { var doc = getBrowser().contentDocument; if (stumbleid == 0) return; var frater = su_get_element("firstrater"); var firstrater = frater.firstrater; su_set_location( "http://" + firstrater + "." + su_servername + "/", null, su_new_tab(event)); } // sets the tabbrowser location, to one of the user's profile tabs function su_set_profile_location(profile_tab, new_tab) { var nick = su_ds.getValue("$nick"); var go_url = ''; if (nick == '') go_url = "http://" + stumbleid + "." + su_servername + "/"; else go_url = "http://" + nick + "." + su_servername + "/"; if (profile_tab != '') go_url += profile_tab + "/"; su_set_location(go_url, null, new_tab); } // sets the tabbrowser location, when the location is beneath the // www stumbleupon domain function su_set_server_location(url_suffix, postdata, new_tab) { su_set_location(su_base_url + url_suffix, postdata, new_tab, null) } function su_set_server_location_signup(new_tab) { var params = ""; var loc = "signup.php"; if (su_host.dist) loc = "sign_up.php"; params = su_arp(params, "version", su_useragent); if (su_host.dist) loc = su_arp(loc, "dist", su_host.dist, true); if (su_ds.getValue("@facebook_user")) loc = su_arp(loc, "pre", "facebook", true); su_set_server_location( loc, params, new_tab); } // sets the tabbrowser location function su_set_location(uri, postdata, new_tab, opt_detail) { if ((typeof opt_detail) == "undefined") opt_detail = null; var browser = getBrowser(); if (new_tab) { var tab = browser.addTab( uri, su_get_nsiuri(browser.contentDocument.referrer), null, // charset (postdata == null) ? null : su_get_mime_input_stream(postdata, "application/x-www-form-urlencoded")); browser.selectedTab = tab; tab.su_detail = opt_detail; } else { browser.selectedTab.su_detail = opt_detail; browser.webNavigation.loadURI( uri, Components.interfaces.nsIWebNavigation.LOAD_FLAGS_NONE, su_get_nsiuri(browser.contentDocument.referrer), (postdata == null) ? null : su_get_mime_input_stream(postdata, "application/x-www-form-urlencoded"), null); // headers } } // Handler for button "Website Info" function su_website_info(new_tab, theurl, firstrate) { if (su_ds.getValue("$review_new_window")) new_tab = true; if (stumbleid == 0) return; var current_page = theurl; if (theurl == "") { current_page = su_get_browser_url(); if (stumbled_redirect != '' && current_page == stumbled_redirect) { // we have a redirect, rate the original url we stumbled on current_page = stumbled_url; } } var cmp_url = current_page.toLowerCase(); if (cmp_url.indexOf("http://video." + su_servername + "/#p") == 0) return; if (cmp_url.indexOf("http://video." + su_servername + "/?p") == 0) return; var stumblevideo = (su_get_stumblevideo_detail() != null); if (current_page.indexOf("about:") == 0) return; if ((su_quote == "") && getBrowser().contentWindow.getSelection) { quote = getBrowser().contentWindow.getSelection().toString(); } else { quote = su_quote; su_quote = ""; } var searchbox_value = su_get_element("su_searchbox").value; if ((! su_ds.getValue("$show_field")) || (searchbox_value == su_tag_instructions) || su_validate_tagstring(searchbox_value)) { searchbox_value = ""; } var current_page2 = current_page; if (current_page2.length > 300) current_page2 = current_page2.substr(0, 300); if ((! stumblevideo) && su_photoblogimage) { su_set_server_location( "url.php?url=" + encodeURIComponent(current_page2) + "&image=" + encodeURIComponent(su_photoblogimage.src) + "&width=" + su_photoblogimage.width + "&height=" + su_photoblogimage.height + "&firstrate=" + firstrate + "&tag=" + escape(searchbox_value), null, new_tab); su_photoblogimage = null; } else if ((! stumblevideo) && (quote != "")) { su_set_server_location( "url.php?url=" + encodeURIComponent(current_page2) + ""e=" + encodeURIComponent(quote) + "&firstrate=" + firstrate + "&tag=" + escape(searchbox_value), null, new_tab); } else { su_set_server_location( "url/" + su_review_url(current_page), null, new_tab); // setTimeout( // su_set_server_location, // 3000, // "url/" + su_review_url(current_page, true), // null, // new_tab); } } function su_review_url(url, new_impl) { // strip off the http:// if (url.match(/^http:\/\//i)) url = url.substr(7); url = encodeURIComponent(url); url = encodeURIComponent(url); url = url.replace(/%252F/g, "/"); return url; } // Check to see if an email is valid function su_validate_email(str) { // var filter=/^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i; var filter = /^([a-zA-Z0-9_\.\-+])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/; if (filter.test(str)) return(true); else return(false); } function su_remove_email(email) { if (!(window.confirm("Are you sure that you want to delete the email address '" + email + "'"))) return; var contact = su_ds.selectRow("contact", "email", email); if (! contact) return; contact.hidden = true; su_ds.updateRow(contact); su_ds.flushPrefs(); su_refresh_referral_menu(2); } // Handler for menuitem from mailto menu function su_mailit(recipient_email) { if (stumbleid == 0) return; su_unfocus_searchbox(); // Now grab recipient and cache it if (recipient_email == "") { recipient_email = getBrowser().contentWindow.prompt("Please enter the recipient's email address", ""); if (recipient_email == null || recipient_email == "" || typeof(recipient_email) == "undefined") return; } // do an email sanity check if (!su_validate_email(recipient_email)) { alert("Recipient is not a valid email address!"); return; } // Cache the email var contact = su_ds.selectRow("contact", "email", recipient_email); if (contact && contact.hidden) { contact.hidden = false; su_ds.updateRow(contact); } else if (! contact) { contact = new Object(); contact.email = recipient_email; su_ds.insertRow("contact", contact); } su_ds.flushPrefs(); var current_page = su_get_browser_url(); if (current_page.indexOf("about:") == 0) { su_refresh_referral_menu(3); return; } su_unfocus_searchbox(); var detail = new Object(); detail.mode = "email"; detail.target = recipient_email; detail.url = current_page; detail.display_url = su_get_browser_url(null, true); detail.stumblevideo = (su_get_stumblevideo_detail() != null); detail.title = getBrowser().contentDocument.title; detail.dialog_title = "Send to " + detail.target; detail.show_target = su_host.mac; detail.referrer_url = su_get_browser_referrer_url(); window.openDialog( "chrome://stumbleupon/content/sendDialog.xul", "", "chrome,dialog,centerscreen,dependent", detail); } function su_generic_done(res) { var context = res.detail; try { if (res.status != 200) return; } catch (e) { return; } var s = ""; if (typeof(res.responseText) != "undefined") s = res.responseText; if (su_log_communication) su_log("response " + context.request_target, s); su_process_commands(s, context); } // TODO: I suspect this completion method should be used in more places, but we are // too close to a release right now to touch too many code paths. Note that this // is the same code in stumble done, so at least those two should be combined. // function su_verbose_generic_done(res) { var context = res.detail; res.done = true; try { if (res.status != 200) { // Maintenance mode returns 503 with "ERROR xxx" set. // In that case, let the "ERROR" command be handled. var isMaintenanceMode = false; if(res.status == 503) { var commands = res.responseText.split(" "); if(commands.length && (commands[0] == "ERROR")) { // Let it fall through isMaintenanceMode = true; } } if(!isMaintenanceMode) { if (! context.quiet) alert("The stumbleupon.com server is currently down.\nPlease try again, and if you are still having difficulties,\ngo to " + su_base_url + "feedback.php to report the problem\nError : " + res.error + "\nStatus : " + res.status); if (callback) callback("connection error", ancestor_callback, context); return; } } } catch (e) { return; } var s = ""; if (typeof(res.responseText) != "undefined") s = res.responseText; if (su_log_communication) su_log("response " + context.request_target, s); su_process_commands(s, context); } // Handler for menuitem "About" function su_about() { // Redirect to about page getBrowser().contentDocument.location = su_serverhttp + 'about.php?version=' + su_verstring; } function su_get_friends() { var params = ""; params = su_arp(params, "now", su_get_time_s()); params = su_arp(params, "configured", su_ds.getValue("$friends_synced")); su_post_url_server_async( "getfriends.php", params, null, su_get_friends_done, null); } function su_get_friends_done(res) { try { if (res.status != 200) return; } catch (e) { return; } var s = ""; if (typeof(res.responseText) != "undefined") s = res.responseText; if (su_log_communication) su_log("response getfriends.php", s); var context = new Object(); context.quiet = true; su_process_commands(s, context); su_ds.setValue("$friends_synced", "" + su_get_time_s()); } function su_get_facebook_userid() { var fbuserid = su_ds.getValue("#facebook_userid"); if (fbuserid) return fbuserid; var manager = su_get_service( "@mozilla.org/cookiemanager;1", "nsICookieManager"); var cookies = manager.enumerator; var cookie; while (cookies.hasMoreElements()) { cookie = cookies.getNext().QueryInterface( Components.interfaces.nsICookie); if (cookie.host == ".facebook.com") { if (cookie.name == "c_user") { fbuserid = parseInt(cookie.value); break; } } } su_ds.setValue("#facebook_userid", fbuserid); return fbuserid; } function su_get_facebook(doc) { if (stumbleid == 0) return; if (su_ds.getValue("#checking_facebook")) return; su_ds.setValue("#checking_facebook", true); var detail = new Object(); detail.doc = doc; detail.stumbleid = stumbleid; var fbuserid = su_get_facebook_userid(); if (! fbuserid) { su_ds.setValue("#checking_facebook", false); return; } su_post_url_server_async( "getfacebook.php", su_arp("", "id", fbuserid), 15000, su_get_facebook_done, detail); } function su_get_facebook_done(res) { try { if (res.status != 200) return; } catch (e) { return; } var s = ""; if (typeof(res.responseText) != "undefined") s = res.responseText; var detail = res.detail; if (su_log_communication) su_log("response getfacebook.php", s); if (detail.stumbleid != stumbleid) return; su_ds.setValue("#checking_facebook", false); if (! res.aborted) su_ds.setValue("#checked_facebook", true); var context = new Object(); context.quiet = true; su_process_commands(s, context); su_refresh_pagemeta(false, 6); if (detail.doc) su_facebookhome_page(detail.doc); } function su_get_state(migrating) { su_post_url_server_async( "getstate.php", su_arp("", "migrating", ((migrating) ? 1 : 0)), null, su_get_state_done, null); } function su_get_state_done(res) { try { if (res.status != 200) return; } catch (e) { return; } var s = ""; if (typeof(res.responseText) != "undefined") s = res.responseText; if (su_log_communication) su_log("response getstate.php", s); var context = new Object(); context.quiet = true; su_process_commands(s, context, true, 0); } function su_import_contacts() { // hit getcontacts.php, parse, and add non-dupes to menu su_post_url_server_async( "getcontacts.php", null, null, su_import_contacts_done, null); } function su_import_contacts_done(res) { try { if (res.status == 1) return; } catch (e) { return; } if (res.status != 200) return; var s = res.responseText; if (typeof(s) != "object" && typeof(s) != "undefined" && s != "") { var newlines = s.split("\n"); for (var i = 0; i < newlines.length; i++) { if (newlines[i] == "") continue; var lines = newlines[i].split(","); if (lines.length>0) { var email = lines[0]; //invalid email address if (!su_validate_email(email)) continue; var contact = su_ds.selectRow("contact", "email", email); if (! contact) { contact = new Object(); contact.email = email; su_ds.insertRow("contact", contact); } } } su_ds.flushPrefs(); su_refresh_referral_menu(4); } } function su_get_interests() { su_post_url_server_async( "getinterests.php", null, null, su_get_interests_done, null); } function su_get_interests_done(res) { try { if (res.status != 200) return; } catch (e) { return; } var s = ""; if (typeof(res.responseText) != "undefined") s = res.responseText; if (su_log_communication) su_log("response getinterests.php", s); if (typeof(s) != "string") return; su_process_topic_list(s); } function su_dist_time() { var now = su_get_time_s(); var installed = su_ds.getIntValue("@installed"); if (installed == 0) { installed = now; su_ds.setValue("@installed", "" + now); } if (! su_host.dist) return; if (su_dist_time_timer) { // if the user changes, this clears the timeout set for the // previously logged in user clearTimeout(su_dist_time_timer); } var reg_prev = su_ds.getIntValue("@dist_reg"); var interval = 7 * 24 * 60 * 60 * 1000; var id_list_prev = su_ds.getValue("@dist_id_list"); var id_list = su_ds.getValue("@id_list"); if ((reg_prev < (now - interval)) && ((id_list_prev == "") || (id_list_prev != id_list))) { su_ds.setValue("@dist_reg", "" + now); var params = ""; params = su_arp(params, "dist", su_host.dist); params = su_arp(params, "regid", su_ds.getValue("@dist_regid")); params = su_arp(params, "idlist", id_list); params = su_arp(params, "preidlist", id_list_prev); params = su_arp(params, "age", (now - installed)); params = su_arp(params, "visible", (su_ds.getValue("@toolbar-visible")) ? 1 : 0); su_post_url_server_async( "disttime.php", params, null, su_dist_time_done, null); } su_dist_time_timer = setTimeout(su_dist_time, interval - (su_random_delay * 1000)); } function su_dist_time_done(res) { try { if (res.status != 200) return; } catch (e) { return; } su_ds.setValue("@dist_id_list", su_ds.getValue("@id_list")); var s = ""; if (typeof(res.responseText) != "undefined") s = res.responseText; if (su_log_communication) su_log("response disttime.php", s); var context = new Object(); context.quiet = true; su_process_commands(s, context); } // // After a certain period of idle stumble activity, we want to reset // the stumble category back to "All". This takes care of preventing users from // unknowingly being stuck in a category. // function su_test_category_reset() { var last_stumbled = su_ds.getIntValue("$last_stumble"); if(su_selected_category == "0") { // We are already in "all" return; } var last_stumbled = su_ds.getIntValue("$last_stumble"); var category_reset_timeout = su_ds.getValue("@category_reset_timeout"); var timenow = (new Date()).getTime(); var diff = timenow - last_stumbled; if(diff >= category_reset_timeout) { su_set_mode_all(); } } function su_process_quarter_hourly() { su_test_category_reset(); } function su_process_rarely(force_dyn_channels, timeout) { if (su_process_rarely_timer) { // if the user changes, this clears the timeout set for the // previously logged in user clearTimeout(su_process_rarely_timer); } var old_timestamp = su_ds.getIntValue("$process_rarely_timestamp"); var last_stumbled = su_ds.getIntValue("$last_stumble"); var timenow = (new Date()).getTime(); var interval = 48 * 60 * 60 * 1000; // two days var oneweek = 7 * 24 * 60 * 60 * 1000; su_process_slclicks(timeout); if (force_dyn_channels) { su_ds.setValue("$process_rarely_timestamp", timenow); su_check_dyn_channels(); } else if ( ((timenow - old_timestamp) > interval) && ((timenow - last_stumbled) < (8 * oneweek)) ) { su_ds.setValue("$process_rarely_timestamp", timenow); // Routines here run every second day unless the user hasn't // stumbled for two months. -- JW su_check_dyn_channels(); } su_process_rarely_timer = setTimeout(su_process_rarely, interval - (su_random_delay * 1000), false, true); } function su_check_dyn_channels() { var url = "http://cdn.stumble-upon.com/stumblethru.csv"; if (su_test_stumblethru_update) url = su_serverhttp + "stumblethru.csv"; su_ds.setValue("#checked_dyn_channels", true); su_post_url_async( url, null, null, su_check_dyn_channels_done, null); } function su_check_dyn_channels_done(res) { try { if (res.status != 200) return; } catch (e) { return; } var s = ""; if (typeof(res.responseText) != "undefined") s = res.responseText; if (su_log_communication) su_log("response stumblethru.csv", s); if (su_ds.getValue("#installing_favicons")) return; su_ds.setValue("#installing_favicons", true); // Parse response text var items = s.split("\n"); var default_domain_list = su_ds.getValue("$default_thru_domain_list"); var default_domain_flags = new Object(); if (default_domain_list != "") { var domains = default_domain_list.split(" "); for (i = 0; i < domains.length; i++) default_domain_flags[domains[i]] = 1; } var i; var j; var channel; var good_channels = new Object(); var has_favicons = su_ds.getValue("$has_favicons"); var checked_sanity = false; for (i = 0; i < items.length; i++) { if (items[i] == "") continue; // do a sanity check on the first nonempty row if (! checked_sanity) { checked_sanity = true; if (! items[i].match(/^.*\..*,\d+,/)) return; } var domain = items[i].split(",")[0]; var name = items[i].split(",")[2]; good_channels[domain] = 1; channel = su_ds.getThruDomainChannel(domain); var filename = su_get_channel_id(domain) + ".ico"; var url = "http://cdn.stumble-upon.com/images/stumblethru/" + filename; if (su_test_stumblethru_update) url = su_serverhttp + "images/stumblethru/" + filename; if (channel) { channel.name = name; su_ds.updateRow(channel); if ((! has_favicons) || (! su_ds.isResourceInstalled("favicons", filename))) { su_ds.installResource( url, "favicons", filename); } } else { channel = new Object(); channel.domain = domain; channel.name = name; if (default_domain_flags[domain]) channel.show = 1; su_ds.installResource( url, "favicons", filename); su_ds.insertRow("dyn_channel", channel); } } var channels = su_ds.getThruDomainChannels(false); for (i = 0; i < channels.length; i++) { if (! good_channels[channels[i].domain]) su_ds.deleteRow(channels[i]); } } function su_sync(context) { if (su_get_time_s() < su_ds.getIntValue("$sync_retry_time_s")) return; var params = ""; params = su_append_sync_params(params); var context = new Object(); context.quiet = true; context.from_sync = true; su_post_url_server_async( "sync.php", params, 15000, su_sync_done, context); } function su_append_sync_params(params) { params = su_arp(params, "ycur_q", su_ds.getValue("$sync_cur_q")); params = su_arp(params, "ycur_t", su_ds.getValue("$sync_cur_t")); params = su_arp(params, "ycur_s", su_ds.getValue("$sync_cur_s")); params = su_arp(params, "ypre_q", su_ds.getValue("$sync_pre_q")); params = su_arp(params, "ypre_t", su_ds.getValue("$sync_pre_t")); params = su_arp(params, "ypre_s", su_ds.getValue("$sync_pre_s")); params = su_arp(params, "yr", su_ds.getValue("$sync_retry")); params = su_arp(params, "yts", su_ds.getValue("$sync_time_s")); return params; } //!!! Would be better to store in a command buffer. function su_sync_done(res) { var context = res.detail; // if (context.stopped) // return; try { if (res.status != 200) return; } catch (e) { return; } var s = ""; if (typeof(res.responseText) != "undefined") s = res.responseText; if (su_log_communication) su_log("response sync.php", s); su_process_commands(s, context, true, 10); } function su_process_commands(str, opt_context, opt_async, opt_async_interval) { var commands = str.split("\n"); var i; var interval; var context = (opt_context) ? opt_context : new Object(); if (opt_async) { context.async_commands = commands; context.async_interval = (opt_async_interval) ? opt_async_interval : 0; setTimeout(su_process_commands2, 0, context); } else { for (i = 0; i < commands.length; i++) { if (commands[i] == "") continue; su_process_command(commands[i], context); } setTimeout(function () { su_ds.flushPrefs(); }, 100); } } function su_process_commands2(context) { var command = context.async_commands.shift(); if (command != "") su_process_command(command, context); if (context.async_commands.length) { setTimeout(su_process_commands2, context.async_interval, context); } else { su_ds.flushPrefs(); su_refresh_pagemeta(false, 10); } } function su_process_command(command_str, context, opt_command_parts) { try { var val; var el; var detail; var command_parts; if (opt_command_parts) command_parts = opt_command_parts; else command_parts = command_str.split(" "); switch (command_parts[0]) { case "SYNC": if (stumbleid == 0) break; if (su_disable_sync) return; if (command_parts.length >= 2) su_ds.setValue("$sync_time_s", parseInt(command_parts[1])); if (command_parts.length >= 3) su_ds.setValue("$sync_retry", parseInt(command_parts[2])); if (command_parts.length >= 4) { var retry_interval_s = parseInt(command_parts[3]); var retry_time_s = su_get_time_s() + retry_interval_s; su_ds.setValue("$sync_retry_time_s", retry_time_s); setTimeout(su_sync, retry_interval_s * 1000); } break; case "NICK": if (stumbleid == 0) break; if (su_prev_nick != command_parts[1]) { su_prev_nick = command_parts[1]; su_ds.setValue("$nick", command_parts[1]); } break; case "MESSAGE": if (stumbleid == 0) break; su_set_inbox_status('2'); su_register_activity("message-notify"); break; case "FRIENDS": setTimeout(su_process_friends_command, 0, command_str); break; case "SEENCONF": su_process_seenconf_command(command_parts[1], context); break; case "DONE": context.done = true; break; case "KEY": if (context.mode == 1) { context.prekey = command_parts[1]; } else if (context.mode == 2) { context.prekey = command_parts[1]; context.prekey2 = command_parts[2]; } break; case "SQCS": if (stumbleid == 0) break; if (su_ds.getValue("$undelivered_count") == 0) clear_stumbles(); break; case "SQCF": if (stumbleid == 0) break; clear_stumbles(); break; case "META": try { su_process_meta_command(command_parts, context); if (su_log_sync) su_logf(command_str); } catch (e) { su_log_error("META COMMAND", e); } break; case "MEDR": try { su_process_medr_command(command_parts, context); if (su_log_sync) su_logf(command_str); } catch (e) { su_log_error("MEDR COMMAND", e); } break; case "MEDT": try { su_process_medt_command(command_parts, context); if (su_log_sync) su_logf(command_str); } catch (e) { su_log_error("MEDT COMMAND", e); } break; case "BKDA": try { su_process_bkda_command(command_parts, context); if (su_log_sync) su_logf(command_str); } catch (e) { su_log_error("BKDA COMMAND", e); } break; case "BKDR": try { su_process_bkdr_command(command_parts, context); if (su_log_sync) su_logf(command_str); } catch (e) { su_log_error("BKDR COMMAND", e); } break; case "BKDC": try { su_process_bkdc_command(); if (su_log_sync) su_logf(command_str); } catch (e) { su_log_error("BKDC COMMAND", e); } break; case "TOPICS": try { su_process_topics_command(command_parts); } catch (e) { su_log_error("TOPICS COMMAND", e); } break; case "UPDATETOPICS": try { su_update_topics_command(command_parts); } catch(e) { su_log_error("UPDATETOPICS COMMAND", e); } break; case "OK": if (stumbleid == 0) break; if (command_parts.length >= 2) su_ds.setCC(command_parts[1]); break; case "SACK": if (stumbleid == 0) break; context.sack = true; if (command_parts.length >= 2) su_ds.setValue("$sync_time_s", command_parts[1]); if (command_parts.length >= 3) su_ds.setValue("$sync_cur_q", command_parts[2]); if (command_parts.length >= 4) su_ds.setValue("$sync_cur_t", command_parts[3]); if (command_parts.length >= 5) su_ds.setValue("$sync_cur_s", command_parts[4]); if (command_parts.length >= 6) su_ds.setValue("$sync_pre_q", command_parts[5]); if (command_parts.length >= 7) su_ds.setValue("$sync_pre_t", command_parts[6]); if (command_parts.length >= 8) su_ds.setValue("$sync_pre_s", command_parts[7]); break; case "ENABLEG": su_enable_client_features(parseInt(command_parts[1])); break; case "DISABLEG": su_disable_client_features(parseInt(command_parts[1])); break; case "ENABLEU": su_enable_user_features(parseInt(command_parts[1])); break; case "DISABLEU": su_disable_user_features(parseInt(command_parts[1])); break; case "ALLAVATARS": if (stumbleid == 0) break; su_ds.setValue("$has_avatars", false); break; case "TAGGER": if (stumbleid == 0) break; su_enable_user_features(0x2); break; case "FACEBOOK": if (stumbleid == 0) break; switch (command_parts[1]) { case "1": su_ds.setValue("$facebook_added", true); su_ds.setValue("$facebook_linked", false); break; case "2": su_ds.setValue("$facebook_added", true); su_ds.setValue("$facebook_linked", true); break; } break; case "UPGRADE": if (stumbleid == 0) break; su_set_visible("su_upgrade", true); break; case "FIRSTFRIEND": if (stumbleid == 0) break; su_ds.setValue("$firstfriends", command_str); break; // case "SPONSOR": // su_ds.setValue("$sponsor", true); // break; // case "NOSPONSOR": // su_ds.setValue("$sponsor", false); // break; case "REGID": su_ds.setValue("@dist_regid", command_parts[1]); break; case "SETU": if (stumbleid == 0) break; su_process_set_pref_command("$" + command_parts[1], command_parts[2]); break; case "SETG": su_process_set_pref_command("@" + command_parts[1], command_parts[2]); break; case "STUMBLENOW": su_process_stumble_now_command(command_str); break; case "SUPR_TWITTER_LINK": if(stumbleid == 0) break; su_ds.setValue("$twitter_supr_linked", (command_parts[1] == "1") ? true : false); su_refresh_referral_menu(10); break; case "SUPR_FACEBOOK_LINK": if(stumbleid == 0) break; su_ds.setValue("$facebook_supr_linked", (command_parts[1] == "1") ? true : false); su_refresh_referral_menu(11); break; case "SFC": su_process_sync_favorites_count_command(parseInt(command_parts[1])); break; case "SSC": su_process_sync_stumble_count_command(parseInt(command_parts[1])); break; case "SHOWURL": if(context.share) { su_process_showurl_command(command_parts, context); } break; case "ERROR": su_process_error_command(command_parts, context); break; } } catch (e) { su_log_error("PROCESS " + command_parts[0], e, command_str); } } function su_get_browser_centered_window_pos(width, height) { var topWin = window.top; var pos = {}; pos.left = (topWin.outerWidth - width) / 2 + topWin.screenX; pos.top = (topWin.outerHeight - height) / 2 + topWin.screenY; return pos; } function su_process_showurl_command(command_parts, context) { var targetUrl = command_parts[1]; var width = parseInt(command_parts[2]); var height = parseInt(command_parts[3]); var options = "dialog=1,toolbar=0,status=0,resizable=1,scrollbars=1"; if((command_parts.length > 4) && (command_parts[4] != '')) { options = command_parts[4]; } var name = "_blank"; if(context.target) name = "su_" + context.target; var pos = su_get_browser_centered_window_pos(width, height); options += ',left=' + pos.left; options += ',top=' + pos.top; options += ',width=' + width; options += ',height=' + height; window.open(targetUrl, name, options); } function su_process_stumble_now_command(command_str) { var parts = command_str.split(" "); if (parts.length < 2) return; // Treat it just like we treat the through.php command var args = parts[1].split("&"); su_process_stumble_now(args); } function su_process_sync_favorites_count_command(count) { if(su_ds.getValue("@enable_server_counts") && (count != su_ds.getValue("$thumbup_count"))) { su_ds.setValue("$thumbup_count", count); su_thumbup_count_changed(); } } function su_process_sync_stumble_count_command(count) { if(su_ds.getValue("@enable_server_counts") && (count != su_ds.getValue("$stumble_count"))) { su_ds.setValue("$stumble_count", count); su_stumble_count_changed(); } } function su_thumbup_count_changed() { var count = su_ds.getValue("$thumbup_count"); if( (count >= 1) && !su_ds.getValue("$show_info") && !su_ds.getValue("$show_info_user_changed") ) { // Show the info button after the first thumbup. su_ds.setValue("$show_info", true); su_set_visible("su_website_info", true); } if( (count >= 3) && !su_ds.getValue("$show_home") && !su_ds.getValue("$show_home_user_changed") ) { // Show the favorites button after the third thumbup. su_ds.setValue("$show_home", true); su_set_visible("su_profile", true); } } function su_stumble_count_changed() { var count = su_ds.getValue("$stumble_count"); if( (count > 99) && !su_ds.getValue("$show_friends") && !su_ds.getValue("$show_friends_user_changed") ) { // After 100 stumbles, show the "Stumblers" button. su_ds.setValue("$show_friends", true); su_set_visible("su_friends", true); } } function su_process_seenconf_command(ids, context) { if(context && context.oldStumbleReport) { su_process_old_seenconf_command(ids); return; } // It's not an old format stumble request so we expect this to just be a single // publicid. context.confirmed = ids; } function su_process_old_seenconf_command(conf_urlids_str) { var conf_urlids; var seen_urlids; var stumbletimes; var stumbletypes; var stumblereferrals; var str; var i; var j; if (conf_urlids_str == "") return; if (su_ds.getValue("$stumblestats") == conf_urlids_str || conf_urlids_str == "[clear]") { seen_urlids = []; stumbletimes = []; stumbletypes = []; stumblereferrals = []; } else { str = su_ds.getValue("$stumblestats"); seen_urlids = str.split("."); str = su_ds.getValue("$stumbletimes"); stumbletimes = str.split("."); str = su_ds.getValue("$stumbletypes"); stumbletypes = str.split("."); str = su_ds.getValue("$stumblereferrals"); stumblereferrals = str.split("."); conf_urlids = conf_urlids_str.split("."); for (i = 0; i < conf_urlids.length; i++) { for (j = 0; j < seen_urlids.length; j++) { if (conf_urlids[i] == seen_urlids[j]) { seen_urlids.splice(j, 1); stumbletimes.splice(j, 1); stumbletypes.splice(j, 1); stumblereferrals.splice(j, 1); break; } } } } su_ds.setValue("$stumblestats", seen_urlids.join(".")); su_ds.setValue("$stumbletimes", stumbletimes.join(".")); su_ds.setValue("$stumbletypes", stumbletypes.join(".")); su_ds.setValue("$stumblereferrals", stumblereferrals.join(".")); su_ds.setValue("$last_uploaded", (new Date()).getTime()); su_ds.flushPrefs(); } function su_enqueue_command(priority, command) { if (! su_host.places) return; var db = su_ds.getDatabase(); db.a("INSERT INTO command_queue (priority, command) VALUES ("); db.av(priority); db.als(command); db.query(); } function su_count_enqueued_commands(priority) { if (! su_host.places) return; var db = su_ds.getDatabase(); var sql = "SELECT count(*) as count FROM command_queue WHERE priority=" + db.v(priority); var result = db.query(sql); var row; if (row = result.shift()) return row.count; else return 0; } function su_process_topics_command(parts) { if (parts.length < 2) return; parts.shift(); su_process_topic_list(parts.join(" ")); } function su_update_topics_command(parts) { if (parts.length < 2) return; parts.shift(); su_update_topic_list(parts.join(" ")); } function su_process_error_command(parts, context) { if (! context) { su_log("warning: missing context for error"); return; } context.error = true; if (context.quiet) return; su_handle_error(parts[1]); } function su_process_bkda_command(parts, context) { if (! su_host.places) return; if (parts.length < 3) return; var spec = new Object(); spec.domain = parts[1]; spec.timestamp = parseInt(parts[2]); var db = su_ds.getDatabase(); var row; var result; var sql; if (context.from_sync) { sql = "SELECT modified FROM blocked_domain WHERE domain=" + db.q(spec.domain); result = db.query(sql); if (row = result.shift()) { // Ignore obsolete sync commands var offset = spec.timestamp - row.modified; if (offset < (- su_ds.getValue("@server_time_float_s"))) return; } } db.a("INSERT INTO blocked_domain (domain, modified, active) VALUES ("); db.as(spec.domain); db.av(spec.timestamp); db.alv(1); db.query(); } function su_process_bkdr_command(parts, context) { if (! su_host.places) return; if (parts.length < 3) return; var spec = new Object(); spec.domain = parts[1]; spec.timestamp = parseInt(parts[2]); var db = su_ds.getDatabase(); var row; var result; var sql; if (context.from_sync) { sql = "SELECT modified FROM blocked_domain WHERE domain=" + db.q(spec.domain); result = db.query(sql); if (row = result.shift()) { // Ignore obsolete sync commands var offset = spec.timestamp - row.modified; if (offset < (- su_ds.getValue("@server_time_float_s"))) return; } } db.a("INSERT INTO blocked_domain (domain, modified, active) VALUES ("); db.as(spec.domain); db.av(spec.timestamp); db.alv(0); db.query(); } function su_process_bkdc_command() { if (! su_host.places) return; var db = su_ds.getDatabase(); var sql; sql = "UPDATE blocked_domain SET active=0"; db.query(sql); } function su_process_medt_command(parts, context) { if (! su_host.places) return; var field_names = new Array( "urlid", // 1 "tagid", // 2 "timestamp"); // 3 parts.shift(); var spec = new Object(); var i; for (i = 0; i < field_names.length; i++) { if (parts.length > 0) spec[field_names[i]] = parts.shift(); else spec[field_names[i]] = null; if (spec[field_names[i]] == "") spec[field_names[i]] = null; } spec.tagid = parseInt(spec.tagid); var result; var row; var result2; var row2; var id; var ids; var nsiuri; var tags = new Array(); var db = su_ds.getDatabase(); var sql; if (context.from_sync) { sql = "SELECT tag_applied FROM url_tag WHERE urlid=" + db.q(spec.urlid) + " AND tagid=" + db.v(spec.tagid); result = db.query(sql); if (row = result.shift()) { // Ignore obsolete sync commands var offset = spec.timestamp - row.tag_applied; if (offset < (- su_ds.getValue("@server_time_float_s"))) return; } } // if this tag has been applied to another url, keep the tag record sql = "SELECT urlid FROM url_tag WHERE tagid=" + db.v(spec.tagid) + " AND urlid!=" + db.q(spec.urlid) + " LIMIT 1"; result = db.query(sql); var keep_tag = false; if (result.length) keep_tag = true; // if this url has been rated, keep the url record sql = "SELECT rating FROM url WHERE urlid=" + db.q(spec.urlid) + " AND rating!=-1"; result = db.query(sql); var keep_url = false; if (result.length) keep_url = true; if (! keep_url) { // if this url has a non-autotag other than the tag to be nuked, keep the url record sql = "SELECT tagid FROM url_tag WHERE urlid=" + db.q(spec.urlid) + " AND tagid!=" + db.v(spec.tagid) + " AND tagid>1000 AND tagid!=" + db.v(su_video_tagid) + " LIMIT 1"; result = db.query(sql); if (result.length) keep_url = true; } if (su_ds.getValue("$sync_bm_meta")) { var ts = su_ds.getTaggingService(); if (keep_url) { sql = "SELECT tag FROM tag_map WHERE tagid=" + db.v(spec.tagid); result = db.query(sql); while (row = result.shift()) tags.push(row.tag); } else { sql = "SELECT tag FROM url_tag NATURAL JOIN tag_map WHERE url_tag.urlid=" + db.q(spec.urlid); result = db.query(sql); while (row = result.shift()) tags.push(row.tag); tags.push("SU"); // for good measure sql = "SELECT catid FROM url WHERE urlid=" + db.q(spec.urlid); result = db.query(sql); if (row = result.shift()) { if (su_ds.getBMTagFromCatid(row.catid)) tags.push(su_ds.getBMTagFromCatid(row.catid)); } } if (tags.length) { sql = "SELECT url FROM url_tag NATURAL JOIN url_map WHERE url_tag.urlid=" + db.q(spec.urlid) + " AND url_tag.tagid=" + db.v(spec.tagid); result = db.query(sql); for (j = 0; row = result[j]; j++) { nsiuri = su_get_nsiuri(row.url); ts.untagURI(nsiuri, tags); if (! keep_url) su_remove_managed_bookmark(nsiuri); } } } if (! keep_url) { sql = "DELETE FROM url_map WHERE urlid=" + db.q(spec.urlid); db.query(sql); sql = "DELETE FROM url WHERE urlid=" + db.q(spec.urlid); db.query(sql); } if (! keep_tag) { sql = "DELETE FROM tag_map WHERE tagid=" + db.v(spec.tagid); db.query(sql); } sql = "DELETE FROM url_tag WHERE urlid=" + db.q(spec.urlid) + " AND tagid=" + db.v(spec.tagid); db.query(sql); } function su_process_medr_command(parts, context) { if (! su_host.places) return; var field_names = new Array( "urlid", // 1 "timestamp"); // 2 parts.shift(); var spec = new Object(); var i; var j; for (i = 0; i < field_names.length; i++) { if (parts.length > 0) spec[field_names[i]] = parts.shift(); else spec[field_names[i]] = null; if (spec[field_names[i]] == "") spec[field_names[i]] = null; } var result; var row; var db = su_ds.getDatabase(); var sql; if (context.from_sync) { sql = "SELECT rating_applied FROM url WHERE urlid=" + db.q(spec.urlid); result = db.query(sql); if (row = result.shift()) { // Ignore obsolete sync commands var offset = spec.timestamp - row.rating_applied; if (offset < (- su_ds.getValue("@server_time_float_s"))) return; } } if (context.ref_url) su_delete_rating(context.ref_url); var usertags = su_get_db_tags(spec.urlid, false, true, true); if (su_ds.getValue("$sync_bm_meta")) su_remove_thumbup_bookmark(spec.urlid, null, usertags); if (usertags) { sql = "UPDATE url SET rating=-1 WHERE urlid=" + db.q(spec.urlid); db.query(sql); } else { sql = "DELETE FROM url WHERE urlid=" + db.q(spec.urlid); db.query(sql); sql = "DELETE FROM url_map WHERE urlid=" + db.q(spec.urlid); db.query(sql); } } function su_process_meta_command(parts, context) { if (! su_host.places) return; // if ((context.mode == 1) || (context.mode == 2)) // context.count++; var field_names = new Array( "urlid", // 1 "ref_url", // 2 "title", // 3 "catid", // 4 "comment_level", // 5 "score", // 6 "rating", // 7 "rating_applied", // 8 "tagid", // 9 "tag", // 10 "tag_applied"); // 11 parts.shift(); var spec = new Object(); var i; for (i = 0; i < field_names.length; i++) { if (parts.length > 0) spec[field_names[i]] = parts.shift(); else spec[field_names[i]] = null; if (spec[field_names[i]] == "") spec[field_names[i]] = null; } if (context.ref_url) spec.ref_url = context.ref_url; if (context.title) { spec.title = context.title; } else if (spec.title) { try { spec.title = decodeURIComponent(spec.title); } catch (e) { su_log_error("DECODE TITLE", e); } } if (! spec.title) spec.title = spec.ref_url; if (! spec.title) { su_log("missing title"); return; } var db = su_ds.getDatabase(); var sql; var result; var row; var tags = new Array(); var old_catid = null; sql = "SELECT catid FROM url WHERE urlid=" + db.q(spec.urlid); result = db.query(sql); if (row = result.shift()) old_catid = row.catid; var local_catid = su_ds.lookup("url:local_catid", spec.ref_url); if (local_catid) spec.catid = local_catid; else if (spec.catid) spec.catid = parseInt(spec.catid); else if (old_catid) spec.catid = old_catid; else spec.catid = 0; if ((typeof context.rating) != "undefined") spec.rating = context.rating; var tag; if (spec.tag) { spec.tagid = parseInt(spec.tagid); spec.tag_applied = parseInt(spec.tag_applied); if (! spec.tagid) { su_log("missing tagid"); return; } if (! spec.tag_applied) { su_log("missing tag_applied"); return; } if (spec.tagid == su_video_tagid) tag = "video"; else if (context.ref_tag) tag = su_ds.getBMTagFromTag(context.ref_tag); else if (spec.tagid < 1000) tag = su_ds.getBMTagFromCatid(spec.tagid); else tag = su_ds.getBMTagFromTag(spec.tag); if (tag) tags.push(tag); sql = "SELECT rating,rating_applied FROM url WHERE urlid=" + db.q(spec.urlid); result = db.query(sql); if (row = result.shift()) { spec.rating = row.rating; spec.rating_applied = row.rating_applied; if ((spec.rating == 1) && (spec.tagid == su_video_tagid)) context.has_video_favs = true; } else { spec.rating = -1; spec.rating_applied = 0; } } if (spec.rating == null) { sql = "SELECT rating FROM url WHERE urlid=" + db.q(spec.urlid); result = db.query(sql); if (row = result.shift()) spec.rating = row.rating; else spec.rating = -1; } else { spec.rating = parseInt(spec.rating); } if ((spec.rating == -1) && (! spec.tagid)) return; // equivalent to medr plus autotag info var bms = su_ds.getBookmarksService(); var timestamp_us; var itemid; var i; var ts; var nsiuri; var urls; var url; var folderid; /* if ((context.mode == 1) || (context.mode == 2)) { // Mode 1 is the favs batch download // Mode 2 is the custom tags batch download nsiuri = su_get_nsiuri(spec.ref_url); // Only create a bookmark if they don't have this url bookmarked // already. If they already have it somewhere, we'll just apply // tags. if (! su_is_bookmarked(nsiuri)) { //!!! Checking folderid every time is a bit expensive but // probably necessary since we allow interaction during // download. folderid = su_get_supertopic_folderid(spec.catid, true); if (folderid) { itemid = bms.insertBookmark( folderid, nsiuri, bms.DEFAULT_INDEX, spec.title); timestamp_us = spec.rating_applied * 1000000; bms.setItemDateAdded(itemid, timestamp_us); bms.setItemLastModified(itemid, timestamp_us); } } // build the tag set var skip = (su_is_adult_category(spec.catid) && (! su_ds.getValue("$sync_bm_adult"))); tag = su_ds.getBMTagFromCatid(spec.catid); if (tag && (! skip)) tags.push(tag); if ((spec.rating == 1) && (! skip)) tags.push("SU"); // apply tags if (tags.length) { ts = su_ds.getTaggingService(); try { ts.tagURI(nsiuri, tags); } catch (e) { su_log_error("DOWNLOAD TAG", e); } } } */ if (su_ds.getValue("$sync_bm_meta")) { if (context.from_sync) { //!!! need to handle tag.modified when from_sync sql = "SELECT rating,rating_applied FROM url WHERE urlid=" + db.q(spec.urlid); result = db.query(sql); if (row = result.shift()) { var offset = spec.rating_applied - row.rating_applied; if (offset < (- su_ds.getValue("@server_time_float_s"))) { if (spec.tagid) { spec.rating = row.rating; spec.rating_applied = row.rating_applied; } else { return; } } } } } db.a("INSERT OR REPLACE INTO url (urlid,title,catid,rating,rating_applied,comment_level,score) VALUES ("); db.as(spec.urlid); db.as(spec.title); db.av(spec.catid); db.av(spec.rating); db.av(spec.rating_applied); db.av(spec.comment_level); db.alv(spec.score); db.query(); db.a("INSERT OR REPLACE INTO url_map (url,urlid) VALUES ("); db.as(spec.ref_url); db.als(spec.urlid); db.query(); if (spec.tagid && spec.tag && spec.tag_applied) { db.a("INSERT OR REPLACE INTO tag_map (tag,tagid) VALUES ("); db.as(spec.tag); db.alv(spec.tagid); db.query(); db.a("INSERT OR REPLACE INTO url_tag (urlid,tagid,tag_applied) VALUES ("); db.as(spec.urlid); db.av(spec.tagid); db.alv(spec.tag_applied); db.query(); } if ((context.mode == 1) || (context.mode == 2) || (! su_ds.getValue("$sync_bm_meta"))) return; if (old_catid && (spec.catid != old_catid)) su_remove_autotag(spec.urlid, old_catid); if ((spec.rating >= 1) && ((! su_is_adult_category(spec.catid)) || su_ds.getValue("$sync_bm_adult"))) { su_add_thumbup_bookmark(spec.urlid, spec.title, spec.catid); } else { var usertags = su_get_db_tags(spec.urlid, false, true, true); su_remove_thumbup_bookmark(spec.urlid, spec.title, usertags); } } function su_remove_autotag(urlid, catid) { if (! su_host.places) return; var db = su_ds.getDatabase(); var tag = su_ds.getBMTagFromCatid(catid); var tags = new Array(); tags.push(tag); var ts = su_ds.getTaggingService(); var row; var sql = "SELECT url FROM url_map WHERE urlid=" + db.q(urlid); var result = db.query(sql); while (row = result.shift()) { nsiuri = su_get_nsiuri(row.url); ts.untagURI(nsiuri, tags); } } function su_change_local_catid(url, new_catid) { if (! su_host.places) return; var urlid = su_ds.getUrlid(url); if (! urlid) { su_ds.define("url:local_catid", url, new_catid); return; } var db = su_ds.getDatabase(); var row; var sql; var result; var old_catid; sql = "SELECT catid FROM url WHERE urlid=" + db.q(urlid); result = db.query(sql); if (row = result.shift()) old_catid = row.catid; else return; if (new_catid == old_catid) return; sql = "UPDATE url SET catid=" + db.v(new_catid) + " WHERE urlid=" + db.q(urlid); db.query(sql); if (! su_ds.getValue("$sync_bm_meta")) return; var old_tag = su_ds.getBMTagFromCatid(old_catid); var old_tags = new Array(); old_tags.push(old_tag); var new_tag = su_ds.getBMTagFromCatid(new_catid); var new_tags = new Array(); new_tags.push(new_tag); var ts = su_ds.getTaggingService(); var adult = su_is_adult_category(new_catid); sql = "SELECT url FROM url_map WHERE urlid=" + db.q(urlid); result = db.query(sql); while (row = result.shift()) { nsiuri = su_get_nsiuri(row.url); ts.untagURI(nsiuri, old_tags); if ((! adult) || (adult && su_ds.getValue("$sync_bm_adult"))) ts.tagURI(nsiuri, new_tags); } } function su_get_db_tags(urlid, include_autotags, include_usertags, include_adult_tags) { var tags = new Array(); var db = su_ds.getDatabase(); var sql; var result; var row; if (include_autotags && (! include_usertags)) sql = "SELECT tag,tag_map.tagid FROM url_tag NATURAL JOIN tag_map WHERE url_tag.urlid=" + db.q(urlid) + " AND (url_tag.tagid<1000 OR url_tag.tagid=" + db.v(su_video_tagid) + ")"; else if ((! include_autotags) && include_usertags) sql = "SELECT tag,tag_map.tagid FROM url_tag NATURAL JOIN tag_map WHERE url_tag.urlid=" + db.q(urlid) + " AND url_tag.tagid>=1000 AND url_tag.tagid!=" + db.v(su_video_tagid); else sql = "SELECT tag,tag_map.tagid FROM url_tag NATURAL JOIN tag_map WHERE url_tag.urlid=" + db.q(urlid); result = db.query(sql); while (row = result.shift()) { if ((! include_adult_tags) && su_is_adult_category(row.tagid)) continue; tags.push(su_ds.getBMTagFromTag(row.tag)); } if (include_autotags) { tags.push("SU"); sql = "SELECT catid FROM url WHERE urlid=" + db.q(urlid); result = db.query(sql); if (row = result.shift()) { if ((include_adult_tags || (! su_is_adult_category(row.catid))) && su_ds.getBMTagFromCatid(row.catid)) tags.push(su_ds.getBMTagFromCatid(row.catid)); } } return (tags.length) ? tags : null; } function su_add_thumbup_bookmark(urlid, title, catid) { var db = su_ds.getDatabase(); var bms = su_ds.getBookmarksService(); var ts = su_ds.getTaggingService(); var tags = su_get_db_tags(urlid, true, true, su_ds.getValue("$sync_bm_adult")); var sql; var result; var row; var result2; var row2; var folderid; var bookmarked; var itemid; var ids; var id; if (! tags) tags = new Array(); // get all urls mapped to this urlid sql = "SELECT url FROM url_map WHERE urlid=" + db.q(urlid); result = db.query(sql); while (row = result.shift()) { nsiuri = su_get_nsiuri(row.url); ids = bms.getBookmarkIdsForURI(nsiuri, []); bookmarked = false; while (id = ids.shift()) { folderid = bms.getFolderIdForItem(id); // if the bookmark is in one of our managed bookmark folders, // remove it sql = "SELECT label FROM supertopic WHERE bm_folderid=" + db.v(folderid); result2 = db.query(sql); if (row2 = result2.shift()) { if (row2.label == su_tagged_folder_name) { bms.removeItem(id); su_check_managed_folder_emptiness(folderid); } else bookmarked = true; } } if (! bookmarked) { folderid = su_get_supertopic_folderid(catid, true); if(folderid) { itemid = bms.insertBookmark( folderid, nsiuri, bms.DEFAULT_INDEX, title); } } ts.tagURI(nsiuri, tags); } } function su_remove_thumbup_bookmark(urlid, title, usertags) { var db = su_ds.getDatabase(); var bms = su_ds.getBookmarksService(); var ts = su_ds.getTaggingService(); var autotags = su_get_db_tags(urlid, true, false, true); var sql; var result; var row; // get all urls mapped to this urlid sql = "SELECT url FROM url_map WHERE urlid=" + db.q(urlid); result = db.query(sql); while (row = result.shift()) { nsiuri = su_get_nsiuri(row.url); var removed_spec = su_remove_managed_bookmark(nsiuri, autotags); // If the url still has tags and isn't bookmarked // elsewhere, add it to the Unfiled/Tagged folder. if (usertags && (! su_is_bookmarked(nsiuri))) { var timestamp_us; if (removed_spec) { title = removed_spec.title; timestamp_us = removed_spec.timestamp_us; } else { title = (title) ? title : row.url; timestamp_us = su_get_time_s() + 1000000; } // get all bookmark items mapped to the urlid folderid = su_get_supertopic_folderid(-1, true); if(folderid) { itemid = bms.insertBookmark( folderid, nsiuri, bms.DEFAULT_INDEX, title); bms.setItemDateAdded(itemid, timestamp_us); bms.setItemLastModified(itemid, timestamp_us); } } if (usertags) ts.tagURI(nsiuri, usertags); else if (autotags) ts.untagURI(nsiuri, autotags); } } function su_remove_managed_bookmark(nsiuri, autotags) { var db = su_ds.getDatabase(); var bms = su_ds.getBookmarksService(); var hs = su_ds.getHistoryService(); var ts = su_ds.getTaggingService(); var folderid; var sql; var result; var query; var ids; var id; var removed_spec = null; ts.untagURI(nsiuri, ["SU"]); if (autotags) ts.untagURI(nsiuri, autotags); ids = bms.getBookmarkIdsForURI(nsiuri, []); while (id = ids.shift()) { folderid = bms.getFolderIdForItem(id); // if the bookmark is in one of our managed bookmark folders, // remove it sql = "SELECT label FROM supertopic WHERE bm_folderid=" + db.v(folderid); result = db.query(sql); if (result.length) { removed_spec = new Object(); removed_spec.title = bms.getItemTitle(id); removed_spec.timestamp_us = bms.getItemLastModified(id); bms.removeItem(id); su_check_managed_folder_emptiness(folderid); } } return removed_spec; } function su_check_managed_folder_emptiness(folderid) { var hs = su_ds.getHistoryService(); var query; var result; var bms; var db; var sql; // if the managed folder is now empty, remove it. query = hs.getNewQuery(); query.setFolders([folderid], 1); result = hs.executeQuery(query, hs.getNewQueryOptions()); result.root.containerOpen = true; if (result.root.childCount == 0) { bms = su_ds.getBookmarksService(); bms.removeItem(folderid); db = su_ds.getDatabase(); sql = "DELETE FROM supertopic WHERE bm_folderid=" + db.v(folderid); db.query(sql); } } function su_get_rating(url, stumblevideo, opt_url_detail) { if (opt_url_detail) return opt_url_detail.rating; if (su_host.places && ! stumblevideo) { var db = su_ds.getDatabase(); var result; var row; var sql; sql = "SELECT rating FROM url_map NATURAL JOIN url WHERE url=" + db.q(url); result = db.query(sql); if (row = result.shift()) { return (row.rating == -1) ? null : row.rating; } else if ((typeof su_ratings[url]) != "undefined") { // We're generating too many hits. if (! su_ds.lookup("url:rating_getmeta_flag", url)) { su_ds.define("url:rating_getmeta_flag", url, 1); su_rate_getmeta(url, false); } return su_ratings[url]; } else { return null; } } else { if ((typeof su_ratings[url]) == "undefined") return null; else return su_ratings[url]; } } function su_get_tag_list(url) { var retval = null; if (((typeof (su_tag_lists_by_url[url])) != "undefined") && (su_tag_lists_by_url[url] != "")) { retval = su_tag_lists_by_url[url]; } else if (su_host.places) { var db = su_ds.getDatabase(); var result; var row; var sql; var tags = new Array(); sql = "SELECT tag FROM url_map NATURAL JOIN url_tag NATURAL JOIN tag_map WHERE url=" + db.q(url) + " AND url_tag.tagid>1000 AND url_tag.tagid!=" + db.v(su_video_tagid); result = db.query(sql); if (result.length) { while (row = result.shift()) tags.push(row.tag); retval = tags.join(", "); su_tag_lists_by_url[url] = retval; } } return retval; } // returns true/false is domain is blocked or not function su_is_domain_blocked(domain) { if (! su_host.places) return false; var out = false; try { var db = su_ds.getDatabase(); var sql; var result; sql = "SELECT active FROM blocked_domain WHERE domain=" + db.q(domain) + " AND active=1"; result = db.query(sql); out = (result.length) ? true : false; } catch (e) {} // be safe since this is within the stumbling path return out; } function su_is_bookmarked(nsiuri) { return (PlacesUtils.getMostRecentBookmarkForURI(nsiuri) != -1) } function su_get_supertopic_folderid(catid, create) { var folder_name; if (catid == 0) catid = -1; else if (su_is_adult_category(catid) && (! su_ds.getValue("$sync_bm_adult"))) catid = -1; if (catid == -1) { folder_name = su_tagged_folder_name; } else { folder_name = su_ds.lookup("catid:folder_name", catid); if (! folder_name) return null; } su_verify_bookmarks_folder(); var bms = su_ds.getBookmarksService(); // If a folder with this name exists in their su bookmarks folder, // use it. var folderid = bms.getChildFolder( su_ds.getValue("$bm_folderid"), folder_name); if (folderid != 0) return folderid; // Otherwise, try to use the most recent one that we created, even // if they moved or renamed it. var db = su_ds.getDatabase(); var result; var index; var row; var sql; sql = "SELECT bm_folderid FROM supertopic WHERE label=" + db.q(folder_name); result = db.query(sql); index = -1; if (row = result.shift()) { folderid = row.bm_folderid; index = bms.getItemIndex(folderid); } if (index != -1) return folderid; else if (! create) return null; // Do a sanity check to make sure we're allowed to create it. if ((folder_name == "Adult") && (! su_ds.getValue("$sync_bm_adult"))) return null; // Create a new one in alphabetical order with our other // automatically generated supertopic folders; make the // 'Other Tagged' folder always last. index = -1; if (catid != -1) { sql = "SELECT label,bm_folderid FROM supertopic WHERE label>" + db.q(folder_name) + " AND label!=" + db.q(su_tagged_folder_name) + " ORDER BY label LIMIT 1"; result = db.query(sql); if (row = result.shift()) { try { index = bms.getItemIndex(row.bm_folderid); } catch (e) {} } } folderid = null; try { folderid = bms.createFolder( su_ds.getValue("$bm_folderid"), folder_name, index); var index2 = bms.getItemIndex(folderid); db.a("INSERT OR REPLACE INTO supertopic (label,bm_folderid) VALUES ("); db.as(folder_name); db.alv(folderid); db.query(); } catch (e) { su_log_error("CREATE FOLDER", e); } // Update the video query to include this new folder. if (folderid) su_refresh_video_folder_bm(); return folderid; } function su_refresh_video_folder_bm() { var db = su_ds.getDatabase(); var sql; var result; var row; sql = "SELECT bm_folderid FROM supertopic ORDER BY label"; result = db.query(sql); var i; var folderids = new Array(); for (i = 0; row = result[i]; i++) folderids.push(row.bm_folderid); var bms = su_ds.getBookmarksService(); var itemid = su_ds.getValue("$bm_suvid_itemid"); var tmpidx; if (itemid != 0) { tmpidx = -1; try { tmpidx = bms.getItemIndex(itemid); } catch (e) {} if (tmpidx != -1) bms.removeItem(itemid); } itemid = su_add_query_folder_bm( su_ds.getValue("$bm_folderid"), folderids, "video", "Video Favorites", 0); su_ds.setValue("$bm_suvid_itemid", itemid); su_ds.flushPrefs(); } function su_get_error_object_dump(o) { if (! o) return "\n" + (typeof o); var str = "\n===== dump ===\n"; var p; for (p in o) { if (p.match(/.*_ERR$/)) continue; try { str += "[" + p + "]\n" + o[p] + "\n"; } catch (e) { str += "[" + p + "] ERROR\n" + e + "\n"; } } str += "========"; return str; } function su_enable_client_features(enable_mask) { var old_bits = su_ds.getValue("@client_form"); // add new enable routines immediately above su_ds.setValue("@client_form", (old_bits | enable_mask)); } function su_disable_client_features(disable_mask) { var old_bits = su_ds.getValue("@client_form"); // add new disable routines immediately above su_ds.setValue("@client_form", (old_bits & (~ disable_mask))); } function su_enable_user_features(enable_mask) { var old_bits = su_ds.getValue("$form"); if (su_ds.hasFeature("$sociallinks", enable_mask) && (! su_ds.hasFeature("$sociallinks", old_bits))) { var searchlinks_enabled = (su_ds.getValue("$show_searchlinks_score") || su_ds.getValue("$show_searchlinks_friends") || su_ds.getValue("$show_searchlinks_topic")); su_ds.setValue("$shown_searchlinks_dialog", searchlinks_enabled); if (! searchlinks_enabled) su_ds.setValue("$intro_count", 0); } if (su_ds.hasFeature("$adultrrecat", enable_mask) && (! su_ds.hasFeature("$adultrrecat", old_bits))) { su_ds.setValue("$recat_adult", 1); } if (su_ds.hasFeature("$adultxrecat", enable_mask) && (! su_ds.hasFeature("$adultxrecat", old_bits))) { su_ds.setValue("$recat_adult", 2); } if (su_ds.hasFeature("$tagger", enable_mask) && (! su_ds.hasFeature("$tagger", old_bits))) { su_ds.setValue("$show_tag", true); su_ds.setValue("$show_flag", true); su_ds.setValue("$shown_tag", true); su_init_toolbar_element_visibility(); } if (su_ds.hasFeature("$has_subscriptions", enable_mask) && (! su_ds.hasFeature("$has_subscriptions", old_bits))) { // If they have subscribers, then turn on the stumblers menu. if(!su_ds.getValue("$show_friends_user_changed")) { su_ds.setValue("$show_friends", true); su_set_visible("su_friends", true); } } // add new enable routines immediately above su_ds.setValue("$form", (old_bits | enable_mask)); } function su_disable_user_features(disable_mask) { var old_bits = su_ds.getValue("$form"); // add new disable routines immediately above su_ds.setValue("$form", (old_bits & (~ disable_mask))); } function su_process_set_pref_command(name, val_str) { switch (su_ds.getPrefType(name)) { case "Int": su_ds.setValue(name, parseInt(val_str)); break; case "Bool": su_ds.setValue(name, ((val_str == "1") || (val_str == "true"))); break; case "Char": su_ds.setValue(name, val_str); break; case "JSON": su_ds.setValue(name, su_ds.deserialize(val_str)); break; } } function su_http_error(error, status) { alert("The stumbleupon.com server is currently down.\nPlease try again, and if you are still having difficulties,\ngo to " + su_base_url + "feedback.php to report the problem\nError : " + error + "\nStatus : " + status); } // initializes stumbleid and stumblepass; also sets the use_token // preference during migration function su_init_login(skip_cookies, ignore_cookies) { try { if (su_ds.isPrefDefined("@current_user")) { var tmp_id = su_ds.getValue("@current_user"); if (tmp_id == "") { stumbleid = 0; stumblepass = ""; } else { stumbleid = tmp_id; stumblepass = su_ds.getStoredPassword(); if ((stumblepass == null) || (stumblepass == "")) { try { su_log_error("NULL PASSWORD"); } catch (e) {} su_ds.setValue("@current_user", ""); stumbleid = 0; stumblepass = ""; return false; } } } else { stumbleid = 0; stumblepass = ""; } if (! skip_cookies) { try { su_process_cookies(ignore_cookies); } catch (e) { su_log_error("INIT COOKIES", e); } } } catch (e) { su_log_error("INIT LOGIN", e); stumbleid = 0; stumblepass = ""; } su_ds.getValue("@current_user"); su_ds.flushPrefs(); return true; } function su_process_cookies(clear_only) { var manager = su_get_service( "@mozilla.org/cookiemanager;1", "nsICookieManager"); var cookies = manager.enumerator; var cookie; var userid1 = null; var password1 = null; var userid2 = null; var password2 = null; var now = (new Date()).getTime(); var searchlinks = null; var nickname = null; var enableg = null; var enableu = null; var disableg = null; var disableu = null; var thru_domains = null; while (cookies.hasMoreElements()) { cookie = cookies.getNext().QueryInterface( Components.interfaces.nsICookie); if ((cookie.host == ("." + su_servername)) && ((cookie.expires * 1000) > now)) { if (cookie.name == "tsuu") { userid1 = cookie.value; manager.remove("." + su_servername, "tsuu", "/", 0); } else if (cookie.name == "tsut") { // As of 2008-04-15, this is always salted, hashed and // not encoded. password1 = cookie.value; manager.remove("." + su_servername, "tsut", "/", 0); } else if (cookie.name == "stumble_user") { userid2 = cookie.value; manager.remove("." + su_servername, "stumble_user", "/", 0); } else if (cookie.name == "stumble_pass") { // As of 2008-04-15, this is always salted, hashed and // not encoded. password2 = cookie.value; manager.remove("." + su_servername, "stumble_pass", "/", 0); } else if (cookie.name == "nickname") { nickname = cookie.value; manager.remove("." + su_servername, "nickname", "/", 0); } else if (cookie.name == "searchlinks") { searchlinks = true; manager.remove("." + su_servername, "searchlinks", "/", 0); } else if (cookie.name == "thru_domains") { thru_domains = cookie.value; manager.remove("." + su_servername, "thru_domains", "/", 0); } else if (cookie.name == "enableu") { enableu = parseInt(cookie.value); manager.remove("." + su_servername, "enableu", "/", 0); } else if (cookie.name == "enableg") { enableg = parseInt(cookie.value); manager.remove("." + su_servername, "enableg", "/", 0); } else if (cookie.name == "disableu") { disableu = parseInt(cookie.value); manager.remove("." + su_servername, "disableu", "/", 0); } else if (cookie.name == "disableg") { disableg = parseInt(cookie.value); manager.remove("." + su_servername, "disableg", "/", 0); } else if (clear_only && ((typeof cookie.name) == "string") && (cookie.name.indexOf("NSC_") == 0)) { manager.remove("." + su_servername, cookie.name, "/", 0); } } } if (clear_only) return null; var profile_change = null; if ((userid1 != null) && (password1 != null) && (userid1 != "") && (password1 != "")) { var login = true; if ((stumbleid != 0) && (stumblepass != "")) { var name = su_ds.getValue("$nick"); if (name == "") name += stumbleid; if (su_ds.getValue("~visited_signup")) { login = true; } else { login = window.confirm("Do you want to sign-in to this new account?\n\n") } } if (login) { profile_change = new Object(); stumbleid = userid1; su_ds.setValue("@current_user", stumbleid); profile_change.new_profile = (! su_ds.isPrefDefined("$nick")); stumblepass = password1; su_ds.storePassword(stumblepass, null); } } else if ((userid2 != null) && (password2 != null) && (userid2 != "") && (password2 != "")) { profile_change = new Object(); stumbleid = userid2; su_ds.setValue("@current_user", stumbleid); profile_change.new_profile = (! su_ds.isPrefDefined("$nick")); if (password2.length < 28) { if (su_enable_hashed_password) { stumblepass = su_ds.getEncodedPassword(password2, stumbleid); su_ds.storePassword(stumblepass, null); } else { stumblepass = password2; su_ds.storePassword(null, stumblepass); } } else { stumblepass = password2; su_ds.storePassword(stumblepass, null); } } if (stumbleid != 0) { if (searchlinks) { su_ds.setValue("$show_searchlinks_friends", true); su_ds.setValue("$show_searchlinks_score", true); su_ds.setValue("$shown_searchlinks", true); } if (nickname) su_ds.setValue("$nick", nickname); if (enableg) su_enable_client_features(enableg); if (enableu) su_enable_user_features(enableu); if (disableg) su_disable_client_features(disableg); if (disableu) su_disable_user_features(disableu); if (thru_domains) su_ds.setValue("$default_thru_domain_list", thru_domains); manager.remove("." + su_servername, "SU_REMEMBER", "/", 0); } if (profile_change) su_visited_login_page = false; return profile_change; } // used by logout and handle_window_load to clear authentication function su_logout_auth() { // 1. remove username and password su_ds.setValue("@current_user", ""); su_ds.deleteStoredPassword(); // now sync this stuff before we crash su_ds.flushPrefs(); // 2. change current user to 0 stumbleid = 0; stumblepass = ''; // 3. remove cookies stumble_user, stumble_pass, and PHPSESSID // ??? or maybe just all cookies from stumbleupon.com? var cookieManager = su_get_service( "@mozilla.org/cookiemanager;1", "nsICookieManager"); cookieManager.remove("." + su_servername, "PHPSESSID", "/", 0); cookieManager.remove("." + su_servername, "stumble_user", "/", 0); cookieManager.remove("." + su_servername, "stumble_pass", "/", 0); cookieManager.remove("." + su_servername, "SU_REMEMBER", "/", 0); su_logout_server(); } function su_logout_server() { su_post_url_server_async( "session.php", su_arp("", "logout", 1), 15000, su_generic_done); } // used by signup_page() to grab a new stumbleid from the server // and to initialize stumbleid, stumblepass and nick function su_init_new_user(challenge, init_toolbar) { var detail = new Object(); detail.init_toolbar = init_toolbar; // We have no ID yet, hit getid.php su_post_url_server_async( "init_user.php", "challenge=" + challenge + ((su_enable_hashed_password) ? "&hashed=1" : ""), null, su_init_new_user_done, detail); } function su_init_new_user_done(res) { var msg = "StumbleUpon was unable to create an account for you. Please try again later."; try { if (res.status == 1) { alert(msg); return; } } catch (e) { alert(msg); return; } if (res.status != 200) { su_http_error(res.error, res.status); return; } var detail = res.detail; var s = ""; if (typeof(res.responseText) != "undefined") s = res.responseText; if (su_log_communication) su_log("response init_user.php", s); var parsed = s.split("\n"); // Iterate through commands for (var i = 0; i < parsed.length; i++) { if (parsed[i] == "") continue; // Parse command structure var command = parsed[i].split(" "); switch(command[0]) { case "USER": stumbleid = command[1]; su_ds.setValue("@current_user", stumbleid); break; case "PASS": stumblepass = command[1]; break; default: var context = new Object(); su_process_command(parsed[i], context, command); if (context.error) return; break; } } if (su_isInt(stumbleid) && stumbleid != 0 && stumblepass != 0 && stumbleid != false && stumblepass != false && stumblepass.length>0) { su_ds.storePassword(stumblepass, null); su_store_user_interests(); // sync prefs.js in case we crash su_ds.flushPrefs(); if (detail.init_toolbar) { var login_detail = new Object(); login_detail.skip_cookies = false; login_detail.ignore_cookies = true; login_detail.new_user_prompt = true; login_detail.new_profile = true; su_invoke_global_event("login", login_detail); } } else { // spit out an error alert("StumbleUpon was unable to create an account for you. Please try again later."); } } //!!! sometimes fails 0 = notint ??? function su_isInt(elm) { elm = elm.toString(); var pattern = /[^0-9]/; if (pattern.test(elm)) return false; else return true; } // user_cat = incat stumble category ID // Gets an url the users hasn't seen yet from stumbleurls function su_get_unseen_url(user_cat, hit_server, callback, context) { // load stumbles... try { su_load_stumbles(null); } catch (e) { su_log_error("UNSEEN LOAD", e); } if (stumbles.length == 0) { if (hit_server) { // We need to hit the server to get urls if (! context) context = new su_AsyncContext(); context.callbacks.push(callback); su_update_url_cache( user_cat, false, su_get_unseen_url_done, context); // Did we get any urls from server? if (stumbles.length == 0) return false; } else { // we're out of stumbles and we're not hitting the server, so bail return false; } } else { // we have stumbles in our queue, carry on su_get_unseen_url_done('', callback, context); } return true; } function su_get_unseen_url_done(error, callback, context) { if (error == "error") { if (callback) callback("error", context); return; } su_load_stumbles(null); var i; for (i = 0; i < stumbles.length; i++) { // Go through each seen url to see if there's one we haven't seen already if (stumbles[i] == "") continue; if (callback) callback(stumbles[i], context); return; } if (callback) callback("", context); } function clickstumble(event) { if (su_promo_mode && (stumbleid == 0)) { // var user_cat = su_selected_category; // user_cat += ""; // // if (! user_cat) // user_cat = "0"; // // var new_cat_flag = (user_cat != su_ds.getValue("$last_incat")); // su_ds.setValue("$last_incat", user_cat); // // var norm_cat = su_trim(user_cat.toLowerCase()); // if (((norm_cat == "video") || (norm_cat == "videos") || // (norm_cat == "tag_video") || (norm_cat == "tag_videos")) && // (su_host.version != "0.0")) // { // su_stumble_video(su_new_tab(event)); // } // else // { su_handle_promo_click(event, "stumble"); // } return; } stumble(su_new_tab(event)); } function su_AsyncContext() { this.callbacks = new Array(); } function su_cancel_stumble_throttle() { su_stumble_throttled = false; } // Handler for button "Stumble" function stumble(stumble_new_tab, skip_searchlinks_dialog) { try { var newDate = new Date(); var newTime = newDate.getTime(); var oldTime = su_ds.getIntValue("$last_stumble"); // avoid double-click if (! stumble_new_tab) { //!!! Why does this get stuck intermittently for some users? // if (newTime - oldTime < su_ds.getValue("@click_throttle_ms")) // return; if (su_stumble_throttled) { return; } else { su_stumble_throttled = true; setTimeout( su_cancel_stumble_throttle, su_ds.getValue("@click_throttle_ms")); } } if (su_cacheTimer != 0) { clearTimeout(su_cacheTimer); su_cacheTimer = 0; } // See if they are not logged in var getit = su_ds.getValue("@current_user"); if (! getit) { // okay, they are not logged in // see if they've already created/used an account with this toolbar if (su_has_logged_in()) { su_show_signin_dialog(); } else { su_verify_cookie_perms(false); su_set_server_location_signup(false); } su_check_progress_listener(); return; } su_check_progress_listener(); if (stumbleid == 0) return; if (! skip_searchlinks_dialog) { if (su_show_searchlinks_dialog(true, stumble_new_tab, true)) return; } if (! su_ds.getValue("$shown_searchlinks_dialog")) su_ds.incrementValue("$intro_count"); // su_update_verified_reporting(true); var user_cat = su_selected_category; if (! user_cat) user_cat = "0"; var new_cat_flag = (user_cat != su_ds.getValue("$last_incat")); su_ds.setValue("$last_incat", user_cat); var oldDate = new Date(); oldDate.setTime(oldTime); su_ds.setValue("$last_stumble", newTime); if (user_cat == "0") su_ds.setValue("$poll_time_s", su_get_time_s()); su_ds.flushPrefs(); // change icon... su_get_element("su_stumble").image="chrome://stumbleupon/content/skin/stumble2.png"; su_stumble_action_count++; setTimeout( su_reset_stumble_action_indicator, su_ds.getValue("@stumble_action_timeout_ms"), su_stumble_action_count); var norm_cat = su_trim(user_cat.toLowerCase()); if (((norm_cat == "video") || (norm_cat == "videos") || (norm_cat == "tag_video") || (norm_cat == "tag_videos")) && (su_host.version != "0.0")) { su_stumble_video(stumble_new_tab); return; } if (su_stumble_async_context && ((newTime - oldTime) <= su_ds.getValue("@recommend_timeout_ms")) && (! new_cat_flag)) { // If a stumble action is in progress and the category hasn't // changed, we only simulate stumbling. Ideally, the time // comparison above shouldn't be necessary, but we include it as a // failsafe to avoid disabling stumbling if // su_stumble_async_context somehow doesn't get set to null. // -- JW //!!! It would be better to queue stumble actions if they're in // the same topic and if they're to be opened in new tabs. But // this would increase likelihood that a referral (and, more // importantly, a note attached to a referral) may not be seen. // Here are a couple related options: // o Don't consider a referral to have been seen unless the // person lingers on the relevant tab. // o Highlight tabs featuring referrals that haven't been lingered // upon. // o If a pending action not targeting a new tab exists, // implicitly cancel the non-new-tab action, perhaps by // converting it into a new-tab action. // -- JW return; } else if (su_stumble_async_context) { try { // Try shouldn't be necessary, but this eliminates possibility // of an error in the callback execution path breaking // stumbling. -- JW if (su_stumble_async_context && su_stumble_async_context._request) su_service.abortPostAsync(su_stumble_async_context._request); } catch (e) { su_log_error("RECOMMEND ABORT ERROR", e); } } // see if new day is the same as today var newDay = newDate.getDate(); var oldDay = oldDate.getDate(); var newMonth = newDate.getMonth(); var oldMonth = oldDate.getMonth(); var newYear = newDate.getYear(); var oldYear = oldDate.getYear(); if (new_cat_flag) { clear_stumbles(); } var first_of_day = false; if (oldTime != 0) { if (oldDay != newDay || oldMonth != newMonth || oldYear != newYear) { first_of_day = true; // clear stumbles clear_stumbles(); } else if (newTime - oldTime > 1000 * 60 * 60 * 2) { // clear stumbles if you haven't stumbled in the last 2 hours // so our stumbles are "fresh" clear_stumbles(); } } var target_browser = null; if (! stumble_new_tab) target_browser = getBrowser().selectedBrowser; if (typeof(user_cat) == "number" || typeof(user_cat) == "undefined" || user_cat == null || user_cat.indexOf("TAG") == -1) { // clear search/tag box su_old_search = ''; su_get_element("su_searchbox").value = ''; su_last_typed_tag = 0; } else { // put it in the box if (user_cat.indexOf("TAG_") == 0) { var tmp_cat = user_cat.substr(4); // Don't tag with thru domains. tag = su_ds.isThruDomain(tmp_cat) ? "" : tmp_cat; } else if (user_cat.indexOf("USERTAG_") == 0) { var chunk = user_cat.substr(8); chunks = chunk.split('_'); var tag = chunks[1]; var profile = chunks[0]; } else { tag = ''; } su_get_element("su_searchbox").value=tag; su_get_element("su_searchbox").removeAttribute("mode"); su_old_search = tag; su_last_typed_tag = 0; su_visited_searchbox = 1; } var unseen = ""; var context = new su_AsyncContext(); context.user_cat = user_cat; context.timestamp = newTime; context.new_tab = stumble_new_tab; context.target_browser = target_browser; context.quiet = false; context.stumblevideo = false; context.first_of_day = first_of_day; context.skip_count = 0; su_stumble_async_context = context; su_get_unseen_url( user_cat, 1, function(unseen, context) { window.stumble_done(unseen, context); }, context); } catch (e) { if (stumbleid == 0) su_log_error("STUMBLE LOGGED-OUT", e); else su_log_error("STUMBLE LOGGED-IN", e, su_ds.getValue("$last_incat"), su_service.getErrorObjectDump(su_stumble_async_context)); su_stumble_async_context = null; } } function su_stumble_video(new_tab) { var label; if (!(su_promo_mode && (stumbleid == 0))) { su_set_mode("video", "Video", "chrome://stumbleupon/content/skin/video.png", "Stumble! ", "Stumble a video"); } if (new_tab) { su_pending_stumblevideo_stumble = true; su_set_location( "http://video." + su_servername + "/", null, true); } else if (su_is_matching_domain(su_get_browser_url(null, true), "video." + su_servername)) { su_dispatch_click(getBrowser().contentDocument, "stumbleButton"); } else { su_pending_stumblevideo_stumble = true; var params = null; if (su_host.dist) params = su_arp("", "dist", su_host.dist); su_set_location( "http://video." + su_servername + "/", params, false); } } function su_update_message(tab_url_detail, url_detail, url, tld, stumblevideo) { if (! tab_url_detail) return; if (! tab_url_detail.messageid) return; var id = "su_messageOuterBox" + tab_url_detail.messageid; if (su_drawer_timers[id]) return; var el; if (url_detail == tab_url_detail) { el = su_get_element("su_bannerReloadButton" + tab_url_detail.messageid); if (el) el.disabled = true; } else if (stumblevideo && (url != tab_url_detail.url)) { su_close_message(tab_url_detail.messageid, true); } else if ((! stumblevideo) && (tab_url_detail.tld != tld)) { su_close_message(tab_url_detail.messageid, true); } else { el = su_get_element("su_bannerReloadButton" + tab_url_detail.messageid); if (el) el.disabled = false; } } /* function su_update_verified_reporting(enable_reporting) { if (su_enable_freereporting) return; // people can't report a stumble as 404/spam until they actually stumble var disabled = (enable_reporting) ? "false" : "true"; su_get_element("su_report-menu").setAttribute("disabled", disabled); su_get_element("su_flag_adult").setAttribute("disabled", disabled); su_get_element("su_flag_wrongtopic").setAttribute("disabled", disabled); su_get_element("su_flag_duplicate").setAttribute("disabled", disabled); su_get_element("su_flag_inaccurate").setAttribute("disabled", disabled); su_get_element("su_flag_spam").setAttribute("disabled", disabled); su_get_element("su_flag_broken").setAttribute("disabled", disabled); su_get_element("su_flag_wronglanguage").setAttribute("disabled", disabled); } */ function su_update_comment_level(url_detail, rateable) { if (url_detail && url_detail.comment_level) su_set_image("su_website_info", "chrome://stumbleupon/content/skin/bubble" + url_detail.comment_level + ".png"); else if (rateable) su_set_image("su_website_info", "chrome://stumbleupon/content/skin/bubble.png"); else su_set_image("su_website_info", "chrome://stumbleupon/content/skin/bubblex.png"); } function su_update_referral_menu_tooltip(url_detail, stumblevideo) { var el = su_get_element("su_referral_menu"); if (! url_detail) { el.setAttribute("tooltiptext", "Share this page"); return; } if (stumblevideo) el.setAttribute("tooltiptext", "Share this video"); else if (url_detail.catid == 302) el.setAttribute("tooltiptext", "Share this picture"); else el.setAttribute("tooltiptext", "Share this page"); } function su_update_firstrater(url_detail) { if (! url_detail) { su_set_visible("firstrater", false); su_set_visible("su_sponsor", false); su_set_image("su_website_info", "chrome://stumbleupon/content/skin/bubble.png"); su_set_image("su_referral_menu", "chrome://stumbleupon/content/skin/icon_tb_share.png"); return; } if ((url_detail.relationship == "sponsored") || (url_detail.relationship == "friend-sponsored")) { // sponsor // Set and show sponsor button su_set_visible("su_sponsor", true); frater = su_get_element("su_sponsor"); frater.setAttribute("tooltiptext", "This site is sponsored"); } else { // nonsponsor // Hide sponsor button su_set_visible("su_sponsor", false); } if (! url_detail.firstrater_nick) { // Hide firstrater button su_set_visible("firstrater", false); return; } // Set and show firstrater button frater = su_get_element("firstrater"); su_set_visible("firstrater", true); var tooltip = url_detail.firstrater_nick; su_set_label("firstrater", url_detail.firstrater_nick); switch (url_detail.relationship) { case "referral": // this site was sent directly to you by a friend frater.image = "chrome://stumbleupon/content/skin/redman.png"; tooltip += " who sent you: "; break; case "friend": // your friend rate this site frater.image = "chrome://stumbleupon/content/skin/redman.png"; tooltip += " who recommends: "; break; case "friend-sponsored": frater.image = "chrome://stumbleupon/content/skin/redman.png"; tooltip += " who suggested: "; break; case "sponsored": // a non friend rated this site frater.image = "chrome://stumbleupon/content/skin/firstrater.png"; tooltip += " who recommends: "; break; case "firstrater": // a non friend rated this site frater.image = "chrome://stumbleupon/skin/firstrater.png"; tooltip += " who suggested: "; break; } tooltip += url_detail.url; frater.firstrater = url_detail.firstrater_nick; frater.setAttribute("tooltiptext", tooltip); } function su_update_thru_domain(url, tld, url_detail, stumblevideo, from_resource_installed) { if (! url) return; if (! tld) tld = su_get_tld(url); if ((! tld) || (url_detail && stumblevideo)) { su_set_visible("su_mode_domain", false); su_set_image("su_mode_domain", "chrome://stumbleupon/content/skin/topic.png"); return; } var tld_parts = tld.split("."); var i = 0; var domain = null; var cmp = ""; while (tld_parts.length) { var part = tld_parts.pop(); if (part == "") return; if (i == 0) cmp = "." + part; else if (i == 1) cmp = part + cmp; else cmp = part + "." + cmp; if (su_ds.isThruDomain(cmp)) domain = cmp; i++; } if (domain) { if (su_get_element("su_mode_dyn_" + su_get_channel_id(domain))) domain = null; } if ((domain == "wikipedia.org") && su_ds.getValue("$show_mode_wiki")) domain = null; if (! domain) { su_set_visible("su_mode_domain", false); su_set_image("su_mode_domain", "chrome://stumbleupon/content/skin/topic.png"); if (su_info_spec && su_info_spec.domain) su_hide_info(); return; } var favicon_url = su_get_favicon_url(domain); if (favicon_url) { su_set_image("su_mode_domain", favicon_url); } else { su_set_image("su_mode_domain", "chrome://stumbleupon/content/skin/domain.png"); } su_set_visible("su_mode_domain", true); var el = su_get_element("su_mode_domain"); el.setAttribute("onclick", "su_handle_domain_mode_click(event, '" + domain + "');"); el.setAttribute("tooltiptext", "Stumble a page from " + domain); if (stumblevideo) return; if (from_resource_installed) return; if (su_ds.getValue("$shown_thru_domain_info_count") >= su_ds.getValue("~shown_thru_domain_info_count_max")) return; var domains = su_ds.getValue("$shown_thru_domain_info_list").split(":"); for (i = 0; i < domains.length; i++) { if (domains[i] == "") continue; if (domains[i] == domain) return; } su_display_info("thru_domain", domain); } function su_update_topic_and_reporting(tab_url_detail, url_detail, tld, from_stumbled, rec_url) { var el = su_get_element("su_morefrom"); if (el && url_detail && url_detail.topic_name) { el.setAttribute("label", "More from " + url_detail.topic_name); el.setAttribute("tooltiptext", "More from " + url_detail.topic_name); el.setAttribute("hidden", "false"); el.setAttribute("oncommand", "su_select_topic(" + url_detail.catid + ",'" + url_detail.topic_name + "', false);"); } else if (el) { el.setAttribute("hidden", "true"); } // Define the topic button used for display var topics_style = su_ds.getValue("$stumble_topics_style"); var menu_style = (topics_style != 2); // Set the information to the topic button var report_menu = su_get_element("su_stumble_report_menu"); if (menu_style && su_ds.getValue("$stumble_topics")) { su_set_visible("su_stumble_topic", false); var widget_id; switch (topics_style) { case 0: widget_id = "su_stumble_topic_menu_left"; break; case 1: widget_id = "su_stumble_topic_menu_right"; break; } if ((url_detail && url_detail.cur_topic_name) || (tab_url_detail && (tab_url_detail.tld == tld) && tab_url_detail.cur_topic_name)) { var url = (url_detail) ? url_detail.url : tab_url_detail.url; var topic_name = (url_detail) ? url_detail.cur_topic_name : tab_url_detail.cur_topic_name; su_get_element(widget_id + "_popup").removeAttribute("onpopupshowing"); su_get_element(widget_id + "_popup").setAttribute("onpopupshowing", 'su_prepare_stumble_topic_menu(event, "' + url + '");'); if (tab_url_detail && (tab_url_detail == url_detail)) su_remove_attribute(widget_id, "style"); else su_set_attribute(widget_id, "style", "color: #707070;"); if (topics_style == 1) su_set_visible("su_separator7", true); su_set_label(widget_id, topic_name); su_set_visible(widget_id, true); } else { su_set_visible(widget_id, false); su_set_visible("su_separator7", false); } } else { su_set_visible("su_stumble_topic_menu_left", false); su_set_visible("su_stumble_topic_menu_right", false); if (url_detail && url_detail.cur_topic_name && su_ds.getValue("$stumble_topics")) { su_set_label("su_stumble_topic", url_detail.cur_topic_name); su_get_element("su_stumble_topic").removeAttribute("onclick"); su_get_element("su_stumble_topic").setAttribute("onclick", 'su_handle_stumble_topic_click(event, "' + url_detail.url + '");'); su_set_visible("su_stumble_topic", true); su_set_visible("su_separator7", true); } else { su_set_visible("su_stumble_topic", false); su_set_visible("su_separator7", false); } } if ((url_detail && url_detail.cur_topic_name) || (tab_url_detail && (tab_url_detail.tld == tld)) || rec_url) { var url; if (url_detail) url = url_detail.url; else if (rec_url) url = rec_url; else url = tab_url_detail.url; su_get_element("su_stumble_report_popup").removeAttribute("onpopupshowing"); su_get_element("su_stumble_report_popup").setAttribute("onpopupshowing", 'su_prepare_stumble_report_menu(event, "' + url + '");'); report_menu.disabled = false; if (tab_url_detail && (tab_url_detail == url_detail)) report_menu.removeAttribute("style"); else report_menu.setAttribute("style", "color: #707070;"); } else { report_menu.disabled = true; } // Update the separator that may be affected by whether the topic menu is visible. su_set_visible("su_separator_category", su_ds.getValue("$show_topics") || !su_get_element("su_stumble_topic_menu_left").collapsed); } /* function su_update_language(url_detail, from_stumbled) { if ((! from_stumbled) && (! su_enable_freereporting)) return; // Update language UI elements. if (url_detail && url_detail.language) { su_get_element("su_wronglanguage").label='Wrong Language (currently ' + url_detail.language + ')'; su_get_element("su_flag_wronglanguage").label='Flag as Wrong Language (currently ' + url_detail.language + ')'; } else { su_get_element("su_wronglanguage").label='Wrong Language'; su_get_element("su_flag_wronglanguage").label='Flag as Wrong Language'; } } */ function su_update_page_feature_prompt(url) { var service_detail = su_get_service_meta(url, true); if (su_is_matching_domain("facebook.com")) { if (su_ds.getValue("#checked_facebook")) { if (su_ds.getValue("$facebook_linked")) { su_set_visible("su_page_feature_prompt", false); } else { su_set_image("su_page_feature_prompt", "chrome://stumbleupon/content/skin/favicon_facebook.gif"); if (su_ds.getValue("$facebook_added")) su_set_label("su_page_feature_prompt", "Link your Facebook account"); else su_set_label("su_page_feature_prompt", "Share using Facebook"); su_get_element("su_page_feature_prompt").setAttribute("tooltiptext", "Share and browse using the StumbleUpon application on Facebook"); su_set_visible("su_page_feature_prompt", true); } } else { su_get_facebook(null); } } else if (service_detail) { if (0) //su_ds.hasFeature("$slbuttonprompt") && // (! su_ds.getValue("$show_searchlinks_score")) && // (! su_ds.getValue("$show_searchlinks_friends")) && // (! su_ds.getValue("$show_searchlinks_topic")) && // ((! su_ds.getValue("$shown_searchlinks")) || // su_ds.hasFeature("$slbuttonpermaprompt"))) { su_set_image("su_page_feature_prompt", service_detail.icon); su_set_label("su_page_feature_prompt", service_detail.prompt_label); su_get_element("su_page_feature_prompt").setAttribute("tooltiptext", service_detail.prompt_tooltip); su_set_visible("su_page_feature_prompt", true); } else { su_set_visible("su_page_feature_prompt", false); } } else { su_set_visible("su_page_feature_prompt", false); } } function su_update_website_info_promo(url) { var service_detail = su_get_service_meta(url, false); if (url.indexOf(su_base_url + "url") == 0) su_get_element("su_website_info_promo").disabled = true; else su_get_element("su_website_info_promo").disabled = false; if (service_detail) { su_search_service_id = service_detail.id; su_set_image("su_website_info_promo", service_detail.icon); su_set_label("su_website_info_promo", service_detail.prompt_label); su_get_element("su_website_info_promo").setAttribute("tooltiptext", service_detail.prompt_tooltip); } else { su_search_service_id = null; su_set_image("su_website_info_promo", "chrome://stumbleupon/content/skin/bubble.png"); su_set_label("su_website_info_promo", su_get_element("su_website_info_promo").getAttribute("showlabel")); su_get_element("su_website_info_promo").setAttribute("tooltiptext", "People who like this"); } } function su_get_tld(url) { return su_service.getEffectiveTLD(url); } function su_deserialize_url_command_params(unseen, for_load) { var field_names = new Array( "url", // 1 . "catid", // 2 "referrer", // 3 . "actual_url", // 4 . "firstrater", // 5 "firstrater_nick", // 6 "lang_code", // 7 not mime_type? "cluster_type", // 8 . "urlid", // 9 . "publicid", // 10 "comment_level", // 11 "rec_type", // 12 "referral_note", // 13 "referralid", // 14 . "catid2", // 15 "catid3" // 16 ); var a = unseen.split(" "); var spec = new Object(); var i; for (i = 0; i < field_names.length; i++) { if (a.length > 0) spec[field_names[i]] = a.shift(); else spec[field_names[i]] = null; if (spec[field_names[i]] == "") spec[field_names[i]] = null; } if (! spec.url) return null; // spec.load_dateobj = null; spec.redirect_url = spec.url; if (spec.url && spec.url != "") spec.tld = su_get_tld(spec.url); if (! spec.tld) spec.tld = ""; if (spec.cluster_type) spec.cluster_type = parseInt(spec.cluster_type); if (! spec.urlid) spec.urlid = 0; if (for_load) return spec; spec.sender = (spec.firstrater_nick) ? spec.firstrater_nick : spec.firstrater; spec.is_system_referral = ((spec.cluster_type == 4) && spec.sender && (spec.sender.toLowerCase() == "stumbleupon")); spec.is_friend_referral = ((spec.cluster_type == 4) && (! spec.is_system_referral)); if (spec.referral_note) { try { spec.referral_note = decodeURIComponent(spec.referral_note); if (spec.referral_note.length > 5000) spec.referral_note = spec.referral_note.substring(0, 4999); } catch (e) { spec.referral_note = null; su_log_error("BAD REFERRALNOTE", e); } } // spec.referral_note = spec.referral_note.replace(/\|/g, ' '); if (! spec.rec_type) spec.rec_type = 0; if (spec.comment_level) spec.comment_level = parseInt(spec.comment_level); else spec.comment_level = 0; // Augment with category_name, relationship, language spec.display_url = spec.url; spec.stumblevideo = false; spec.cur_catid = spec.catid; spec.topic_name = su_catnames[spec.catid]; if (! spec.topic_name) spec.topic_name = null; spec.cur_topic_name = spec.topic_name; spec.rating = null; var status; // show user's comment (if it's not a referral, and there is a comment) using display_message switch (spec.cluster_type) { case 1: status = "friend"; break; case 3: if (spec.firstrater_nick && su_is_mutual_friend(spec.firstrater_nick)) status = "friend-sponsored"; else status = "sponsored"; break; case 4: status = "referral"; spec.rating = su_get_rating(spec.url, false, null); break; default: status = "firstrater"; break; } spec.relationship = status; spec.language = su_ds.lookup("lang_code:language", spec.lang_code); if (spec.catid2) spec.catid2 = parseInt(spec.catid2); if (spec.catid3) spec.catid3 = parseInt(spec.catid3); spec.eval_interval = 0; spec.shown_dateobj = null; return spec; } function stumble_done(unseen, context) { try { su_stumble_async_context = null; su_get_element("su_stumble").image="chrome://stumbleupon/content/skin/stumble.png"; // ignore excessively delayed responses var delay_ms = ((new Date()).getTime()) - context.timestamp; if (delay_ms > su_ds.getValue("@stumble_action_timeout_ms")) return; if ((unseen == "error") || (unseen == "connection error")) return; if (unseen == "") { su_stumble_done_no_stumbles(context); return; } // Build the url_detail spec. var url_detail = su_deserialize_url_command_params(unseen, false); // url_detail.url = "http://media.tumblr.com/mlsyKxOF8fzc9kd1zQ37q9b8o1_500.jpg"; // url_detail.urlid = "25624734"; // url_detail.tld = su_get_tld(url_detail.url); if (! url_detail) { su_log_error("STUMBLE DESERIALIZE", unseen); clear_stumbles(); su_stumble_done_no_stumbles(context); return; } // These shouldn't be served, but it doesn't hurt to do a sanity // check. if ((url_detail.cluster_type != 4) && su_is_domain_blocked(url_detail.tld)) { su_enqueue_stumblestats(url_detail); su_load_stumbles(url_detail.url); su_save_stumbles(); setTimeout(su_skip_stumble, 0, context); return; } // su_dd("setstumbled", 1, url_detail.url); // Set globals. stumbled_url = url_detail.url; su_redirect_url = url_detail.url; // su_dd("reset", 1); stumbled_redirect = ""; // Record url details. su_ds.define("url:url_detail", stumbled_url, url_detail); // if (url_detail.affiliate_url) // { // su_prefetch_url( // url_detail.affiliate_url, // su_base_url + "refer.php?url=" + escape(url_detail.affiliate_url), // 0); // } // Show the stumble! shown = su_stumble_done_show_stumble(url_detail, context); if (! shown) { su_check_progress_listener(); return; } // Note that we still try to keep the count on the client, and just let the server // override it with SSC after the submission occurs, if necessary. We are doing this primarily // for testing purposes because the toolbar might be pointed at a server that doesn't yet // implement SSC and SFC var stumble_count = su_ds.incrementValue("$stumble_count"); su_stumble_count_changed(); su_enqueue_stumblestats(url_detail); su_log_dd_uc(unseen); if (context.user_cat.indexOf("TAG_") == 0) { var str = context.user_cat.substr(4).toLowerCase(); if (su_ds.isThruDomain(str)) { var spec = su_ds.getValue("#recent_info_spec"); if (spec.domain && spec.domain == str) { if (! su_ds.getValue("$shown_toall_info")) setTimeout(su_display_info, 0, "thru_domain_praise_toall", spec.domain); else if (! su_ds.getValue("$shown_tomore_info")) setTimeout(su_display_info, 0, "thru_domain_praise_tomore", spec.domain); } su_close_info(); } } else if (context.user_cat == "302") { su_ds.setValue("$shown_photo_info", true); var spec = su_ds.getValue("#recent_info_spec"); if ((spec.type == "photo") && (! su_ds.getValue("$shown_toall_info"))) setTimeout(su_display_info, 0, "photo_praise"); su_close_info(); } else if (su_is_image_url(url_detail.url) && (! su_ds.getValue("$shown_photo_info"))) { setTimeout(su_display_info, 0, "photo"); su_close_info(); } else { su_close_info(); } // Remove the url from our local stumble queue. //!!! We want to do // - removal from local queue // - stumbletimes recording // - referral count decriment // after both (a) the page loads enough for the user to have // reviewed content and (b) the user has visited the tab. But // detecting those events is a relatively difficult problem. // -- JW //!!! Are we removing multiple referrals for the same url? -- JW su_load_stumbles(url_detail.url); su_save_stumbles(); // Update topic UI elements. su_update_topic_and_reporting(url_detail, url_detail, url_detail.tld, true, null); // su_update_language(url_detail, true); // Clear old sponsor or firstrater buttons // su_set_visible("su_sponsor", false); // su_set_visible("firstrater", false); // If we have a message, display it. if (url_detail.is_friend_referral || url_detail.referral_note) { setTimeout( su_stumble_done_display_message, 0, url_detail, context.target_browser); } else if ((stumble_count >= 5) && ((su_ds.getValue("$thumbup_count") + su_ds.getValue("$thumbdown_count")) <= 1) && (! su_ds.getValue("$shown_rate_info"))) { su_display_info("rate"); } // If this is a referral, decriment referral count. //!!! May get out of sync if we start sending referrals via the SV // page. -- JW if (url_detail.cluster_type == 4) su_decriment_undelivered_count(); if ((! context.stumblevideo) && (stumbled_url.indexOf(su_serverhttp + "first_stumble.php") != 0)) { // get unseen url, but don't hit the server to do it su_get_unseen_url( context.user_cat, 0, null, null); } su_check_progress_listener(); su_register_activity("stumble"); } catch (e) { su_log_error("STUMBLE DONE", e); } } function su_is_image_url(url) { //!!! Ideally, we should use the content type logic from the // surveyor. -- JW return (url.match(/\.(jpg|jpeg|png|gif)$/) ? true : false); } function su_stumble_done_show_stumble(url_detail, context) { try { su_prefetcher.advancePastTarget(stumbled_url); } catch (e) { su_log_error("PREFETCHER 5", e); } var detail = su_get_async_target_browser( context.target_browser, context.new_tab); if (! detail) return false; context.target_browser = detail.target_browser; if (context.target_browser.su_url_detail && context.target_browser.su_url_detail.messageid) { setTimeout( su_close_message, 0, context.target_browser.su_url_detail.messageid, true); } context.target_browser.su_url_detail = url_detail; //var referrer = su_base_url + "refer.html"; var referrer = su_base_url + "refer.php?url=" + encodeURIComponent(stumbled_url); if (url_detail.referrer) referrer = url_detail.referrer; if (! su_ds.getValue("@enable_refer")) referrer = "about:blank"; if (su_is_adult_category(url_detail.catid)) referrer = url_detail.url; var postdata = ""; if (url_detail.url.indexOf(su_base_url + "signup.php") == 0) postdata = su_get_client_postdata(url_detail.url); var listener = new su_StumbleProgressListener(url_detail, context); try { context.target_browser.addProgressListener(listener); } catch (e) {} // context.target_browser.su_content_clicked = false; try { context.target_browser.webNavigation.loadURI( url_detail.url, 0, su_get_nsiuri(referrer), (postdata == "") ? null : su_get_mime_input_stream(postdata, "application/x-www-form-urlencoded"), null); } catch (e) { su_log_error("LOADURI ERROR4", e, url_detail.url); } return true; } function su_enqueue_stumblestats(url_detail) { if (!url_detail.publicid) return; // Old urlids, don't store, just send var recently_seen = su_ds.getValue("$recently_seen"); var seen_urlids; if (recently_seen == "") seen_urlids = new Array(); else seen_urlids = recently_seen.split("."); // New format, public ids var recently_seen_publicids = su_ds.getValue("$recently_seen_publicids"); var seen_publicids; if(recently_seen_publicids == "") seen_publicids = new Array(); else seen_publicids = recently_seen_publicids.split("."); // Add this public id to recentlyseen seen_publicids.push(url_detail.publicid); while (seen_publicids.length > 50) seen_publicids.shift(); su_ds.setValue("$recently_seen_publicids", seen_publicids.join(".")); // Recently seen referral ids var recently_seen_referralids = su_ds.getValue("$recently_seen_referralids"); var seen_referralids; if(recently_seen_referralids == "") seen_referralids = new Array(); else seen_referralids = recently_seen_referralids.split("."); // Add this referral id to recentlyseen referralids seen_referralids.push(url_detail.referralid); while (seen_referralids.length > 50) seen_referralids.shift(); su_ds.setValue("$recently_seen_referralids", seen_referralids.join(".")); su_ds.flushPrefs(); // Add the visited URL details to the visited table su_stumbleReporter.addVisitedUrl(url_detail); } function su_get_async_target_browser(target_browser, new_tab) { var detail = new Object(); var browser = getBrowser(); if (new_tab) { var characterSet = browser.contentDocument.characterSet; try { var tab = browser.addTab( "about:blank", stumbled_url, null, characterSet); detail.target_browser = browser.getBrowserForTab(tab); browser.selectedTab = tab; } catch (e) { su_log_error("ADDTAB ERROR", e, stumbled_url); } } else { var found = false; for (var i = 0; i < browser.browsers.length; i++) { if (browser.browsers[i] == target_browser) { detail.target_browser = target_browser; found = true; break; } } if (! found) { // Cancel the stumble if, by the time we get here, // they've closed the tab. -- JW detail = null; } } return detail; } function su_decriment_undelivered_count() { // decriment referral count var count = su_ds.getValue("$undelivered_count"); count--; su_ds.setValue("$undelivered_count", count); su_update_referred(true); setTimeout(su_test, 1000); } function su_test() { } function su_stumble_done_no_stumbles(context) { var user_cat = context.user_cat + ""; var detail = su_get_async_target_browser( context.target_browser, context.new_tab); if (! detail) return; var target_browser = detail.target_browser; var target_url; // We couldn't find an unseen url... // Check to make sure this isn't an incat stumble if (user_cat == "0") { // If we got here, we're out of urls, and we're in "Any Topic" //!!! first make sure we are not already here.... target_url = su_base_url + "interests.php?out=1"; target_browser.webNavigation.loadURI( target_url, 0, null, su_get_mime_input_stream( su_get_client_postdata(target_url), "application/x-www-form-urlencoded"), null); // change icon... su_get_element("su_stumble").image = "chrome://stumbleupon/content/skin/stumble.png"; return; //!!! eventually we should cycle through "great history" here } var tag = ""; var mode = ""; var profile = ""; if (su_isInt(user_cat)) { // mode = incat mode = "incat"; su_load_categories(); if (typeof(su_catnames[user_cat]) != "undefined") tag = su_catnames[user_cat]; else tag = ""; } else if (user_cat.indexOf("LANG_") == 0) { mode = "language"; tag = su_ds.lookup("lang_code:language", user_cat.substr(5)); } else if (user_cat.indexOf("TAG_") == 0) { mode = "tag"; tag = user_cat.substr(4); } else if (user_cat.indexOf("USERTAG_") == 0) { mode = "showfriendtag"; var chunk = user_cat.substr(8); chunks = chunk.split('_'); var tag = chunks[1]; var profile = chunks[0]; // alert("tag " + tag + " profile " + profile); } else { if (user_cat == "news") { mode = "news"; tag = "news"; } else if (user_cat == "video") { mode = "video"; tag = "video"; } else if (user_cat == "friends") { mode = "friends"; tag = "friends"; } else if (user_cat == "wiki") { mode = "wiki"; tag = "wiki"; } else { mode = "showfriend"; profile = user_cat; } } target_url = su_base_url + "explore.php?mode=" + mode; if (tag != "") target_url += "&tag=" + tag.toLowerCase(); if (profile != "") target_url += "&showfriend=" + profile.toLowerCase(); if (mode == "incat") target_url += "&topic=" + user_cat; // User is doing an incat stumble // Set user_cat to 0 su_set_mode_all(); // Give them a message explaining they have run out in their particular cat. // grab the current HTML window target_browser.webNavigation.loadURI( target_url, 0, null, su_get_mime_input_stream( su_get_client_postdata(target_url), "application/x-www-form-urlencoded"), null); // change icon... su_get_element("su_stumble").image = "chrome://stumbleupon/content/skin/stumble.png"; } // used by a timeout to ensure that the stumble button icon returns // to vertical within 15 seconds function su_reset_stumble_action_indicator(stumble_action_id) { if (stumble_action_id == su_stumble_action_count) su_get_element("su_stumble").image="chrome://stumbleupon/content/skin/stumble.png"; } // used load_data2 function su_check_referral(force_update) { if (stumbleid == 0) return; var check_now = force_update; if (su_check_referral_timer) { // if the user changes, this clears the timeout set for the // previously logged in user clearTimeout(su_check_referral_timer); } var state = su_ds.getValue("$poll_state"); var interval = su_ds.lookup("state:poll_interval_s", state); var poll_time_s = su_ds.getIntValue("$poll_time_s"); var now_s = su_get_time_s(); var elapsed = now_s - poll_time_s; if (elapsed >= interval) check_now = true; if (check_now) { elapsed = 0; // advance state var new_state = null; switch (state) { case "b": new_state = "c"; break; case "c": new_state = "d"; break; case "d": new_state = "e"; break; case "e": new_state = "f"; break; case "a": case "f": case "g": var activity_time_s = su_ds.getIntValue("$activity_time_s"); if (activity_time_s == 0) activity_time_s = now_s; var idle_interval = now_s - activity_time_s; if (idle_interval > (3600 * 24 * 60)) new_state = "h"; else if (idle_interval > (3600 * 24 * 10)) new_state = "g"; break; } if (new_state) { su_ds.setValue("$poll_state", new_state); interval = su_ds.lookup("state:poll_interval_s", new_state); } su_ds.setValue("$poll_time_s", now_s); var context = new su_AsyncContext(); context.quiet = true; context.user_cat = 0; su_update_url_cache( 0, true, // check_referral su_check_referral_done, context); } su_check_referral_timer = setTimeout(su_check_referral, ((interval - elapsed) * 1000), false); } function su_register_activity(type) { if (stumbleid == 0) return; su_ds.setValue("$activity_time_s", su_get_time_s()); var state = su_ds.getValue("$poll_state"); var new_state = state; switch (type) { case "referred": if (state == "a" || state == "g" || state == "h") new_state = "f"; break; case "referral": if (state == "a" || state == "d" || state == "e" || state == "g" || state == "h") new_state = "b"; break; case "stumble": case "rate": case "message-notify": if (state == "g" || state == "h") new_state = "a"; break; } if (new_state != state) { su_ds.setValue("$poll_state", new_state); su_check_referral(false); } } function su_check_referral_done(error) { if (error == "connection error") setTimeout(su_check_referral_retry, 10000); } function su_check_referral_retry() { // Retry once. This mostly caters to DSL users who have to wait // for the modem to reconnect. -- JW var context = new su_AsyncContext(); context.quiet = true; context.user_cat = 0; su_update_url_cache( 0, true, // check_referral null, context); } function su_show_searchlinks_dialog(new_user_prompt, new_tab, stumble) { var intro_count = su_ds.getValue("$intro_count"); if ((intro_count == 0) || ((intro_count % 15) != 0)) return false; if (su_ds.getValue("$shown_searchlinks_dialog")) return false; su_ds.setValue("$shown_searchlinks_dialog", true); if (su_ds.getValue("$show_searchlinks_score")) return false; if (su_ds.getValue("$show_searchlinks_friends")) return false; if (su_ds.getValue("$show_searchlinks_topic")) return false; window.setTimeout(su_show_searchlinks_dialog_wrapped, 100, new_user_prompt, new_tab, stumble); return true; } function su_show_searchlinks_dialog_wrapped(new_user_mode, new_tab, stumble) { var detail = new Object(); var filename; var social = su_ds.hasFeature("$sociallinks"); if (social && new_user_mode) filename = "social_searchlinks_newuser_prompt.gif"; else if (social) filename = "social_searchlinks_prompt.gif"; else if (new_user_mode) filename = "searchlinks_newuser_prompt.gif"; else filename = "searchlinks_prompt.gif"; if (new_user_mode) detail.preview_serp_url = "http://www.google.com/search?q=StumbleUpon"; else detail.preview_serp_url = null; detail.new_tab = new_tab; detail.prompt_filename = filename; detail.stumble = stumble; su_ds.installResource( "http://cdn.stumble-upon.com/images/" + filename, "images", filename); su_searchlinks_dialog_detail = detail; } function su_handle_searchlinks_dialog_resource_load(detail) { detail.prompt_src = su_ds.getResourceURLFromName( "images", detail.prompt_filename); window.openDialog( "chrome://stumbleupon/content/searchlinksDialog.xul", "", "chrome,dialog,centerscreen,dependent,close=no", detail); } function su_handle_searchlinks_dialog_close(detail) { if (detail.result == "cancel-error") { detail.result = ""; window.openDialog( "chrome://stumbleupon/content/searchlinksDialog.xul", "", "chrome,dialog,centerscreen,dependent,close=no", detail); } else if (detail.result == "yes") { su_ds.setValue("$show_searchlinks_score", true); su_ds.setValue("$show_searchlinks_friends", true); su_ds.setValue("$shown_searchlinks", true); su_ds.flushPrefs(); if (detail.preview_serp_url) { // The timeout and the su_ds.flushPrefs() above work around an // intermittent timing issue where the link behavior isn't // enabled in time for searchlinks to appear in the demo. -- JW setTimeout( su_set_location, 150, detail.preview_serp_url, null, detail.new_tab); } } else { su_ds.setValue("$show_searchlinks_score", false); su_ds.setValue("$show_searchlinks_friends", false); su_ds.setValue("$show_searchlinks_topic", false); } } function su_check_show_position_dialog() { if(su_ds.getValue("$shown_position_dialog")) return false; su_ds.setValue("$shown_position_dialog", true); if(su_ds.getValue("@toolbar-position") != su_ds.getDefaultValue("@toolbar-position")) return false; if(su_ds.getValue("$stumble_count") < 5) return false; var detail = new Object(); window.openDialog( "chrome://stumbleupon/content/positionDialog.xul", "", "chrome,dialog,centerscreen,dependent,close=no", detail); return true; } function su_handle_position_dialog_close(detail) { if (detail.result == "cancel-error") { detail.result = ""; window.openDialog( "chrome://stumbleupon/content/positionDialog.xul", "", "chrome,dialog,centerscreen,dependent,close=no", detail); } else if (detail.result == "yes") { su_move_to_bookmark_bar(); } } function su_stumble_done_display_message(url_detail, target_browser) { //!!! test in FF 1.5, Seamonkey, Flock var box = target_browser.parentNode; var messageid = su_ds.incrementValue("~message_count"); target_browser.su_url_detail.messageid = messageid; // This stack prevents reflow of the banner content upon show/hide. // We could reuse it, but there's no compelling reason to. -- JW var stack = document.createElement("stack"); var outerbox = document.createElement("vbox"); var outerbox_id = "su_messageOuterBox" + messageid; outerbox.setAttribute("id", outerbox_id); outerbox.style.position = "fixed"; outerbox.style.top = "100%"; if (su_host.mac) outerbox.setAttribute("class", "su_pinstripe_bannerBox outset"); else outerbox.setAttribute("class", "su_winstripe_bannerBox outset"); stack.appendChild(outerbox); var grid = document.createElement("grid"); grid.setAttribute("flex", "1"); outerbox.appendChild(grid); var columns = document.createElement("columns"); grid.appendChild(columns); var el; el = document.createElement("column"); columns.appendChild(el); el = document.createElement("column"); el.setAttribute("flex", "1"); columns.appendChild(el); el = document.createElement("column"); columns.appendChild(el); var rows = document.createElement("rows"); rows.setAttribute("flex", "1"); grid.appendChild(rows); var firstrow = document.createElement("row"); if (su_host.mac) firstrow.setAttribute("class", "su_pinstripe_bannerInnerBox"); rows.appendChild(firstrow); var hboxaa = document.createElement("hbox"); hboxaa.setAttribute("align", "center"); firstrow.appendChild(hboxaa); el = document.createElement("image"); el.setAttribute("src", su_get_message_icon_src(url_detail)); el.setAttribute("class", "su_bannerImage"); if (! url_detail.is_system_referral) { el.setAttribute("style", "cursor: pointer;"); el.setAttribute("onclick", "su_handle_message_sender_click(event, " + messageid + ")"); } hboxaa.appendChild(el); el = document.createElement("label"); el.setAttribute("value", url_detail.sender); if (! url_detail.is_system_referral) { el.setAttribute("style", "color: rgb(0,0,238); text-decoration: underline; margin-right:0; cursor: pointer;"); el.setAttribute("onclick", "su_handle_message_sender_click(event, " + messageid + ")"); } hboxaa.appendChild(el); el = document.createElement("label"); el.setAttribute("style", "margin-left: 0"); el.setAttribute("value", su_get_message_label(url_detail)); hboxaa.appendChild(el); var hboxab = document.createElement("hbox"); hboxab.setAttribute("flex", "1"); hboxab.setAttribute("align", "center"); firstrow.appendChild(hboxab); messagedeck = document.createElement("deck"); messagedeck.setAttribute("flex", "1"); messagedeck.setAttribute("align", "center"); hboxab.appendChild(messagedeck); el = document.createElement("textbox"); el.setAttribute("id", "su_bannerLineTextbox" + messageid); el.setAttribute("multiline", "false"); el.setAttribute("value", ""); el.setAttribute("readonly", "true"); el.setAttribute("hidden", "true"); if (su_host.mac) el.setAttribute("class", "su_pinstripe_bannerMessage"); else el.setAttribute("class", "su_winstripe_bannerMessage"); messagedeck.appendChild(el); el = document.createElement("textbox"); el.setAttribute("id", "su_bannerMultilineTextbox" + messageid); el.setAttribute("multiline", "true"); el.setAttribute("value", ""); el.setAttribute("readonly", "true"); el.setAttribute("hidden", "true"); if (su_host.mac) el.setAttribute("class", "su_pinstripe_bannerMessage"); else el.setAttribute("class", "su_winstripe_bannerMessage"); messagedeck.appendChild(el); el = document.createElement("description"); el.setAttribute("id", "su_bannerTextMeasurer" + messageid); el.setAttribute("flex", "1"); el.setAttribute("crop", "end"); el.setAttribute("style", "margin-left: 8px; margin-right: 8px;"); messagedeck.appendChild(el); if (url_detail.is_friend_referral) { el = document.createElement("button"); el.setAttribute("id", "su_bannerReplyButton" + messageid); el.setAttribute("label", "Reply Now"); el.setAttribute("accesskey", "R"); el.setAttribute("oncommand", "su_handle_message_reply_command(" + messageid + ")"); hboxab.appendChild(el); } el = document.createElement("spacer"); el.setAttribute("flex", "1000"); hboxab.appendChild(el); el = document.createElement("button"); el.setAttribute("id", "su_bannerReloadButton" + messageid); if (url_detail.is_friend_referral || url_detail.is_system_referral) el.setAttribute("label", "Reload Sent Page"); else el.setAttribute("label", "Reload Stumbled Page"); el.setAttribute("accesskey", "L"); el.setAttribute("disabled", "true"); el.setAttribute("oncommand", "su_handle_message_reload_command(" + messageid + ")"); hboxab.appendChild(el); var elac = document.createElement("toolbarbutton"); if (su_host.mac) elac.setAttribute("class", "su_pinstripe_messageCloseButton"); else elac.setAttribute("class", "su_winstripe_messageCloseButton"); elac.setAttribute("oncommand", "su_handle_message_close_command(" + messageid + ")"); firstrow.appendChild(elac); var secondrow = document.createElement("row"); secondrow.setAttribute("id", "su_messageSendRow" + messageid); secondrow.setAttribute("hidden", "true"); rows.appendChild(secondrow); var hboxba = document.createElement("hbox"); hboxba.setAttribute("pack", "end"); hboxba.setAttribute("align", "center"); secondrow.appendChild(hboxba); el = document.createElement("label"); el.setAttribute("value", "Reply:"); hboxba.appendChild(el); var hboxbb = document.createElement("hbox"); hboxbb.setAttribute("flex", "1"); secondrow.appendChild(hboxbb); el = document.createElement("textbox"); el.setAttribute("flex", "1"); el.setAttribute("id", "su_messageTextbox" + messageid); el.setAttribute("class", "su_messageTextbox"); el.setAttribute("maxlength", 5000); el.setAttribute("onkeypress", "su_handle_message_keypress(event, " + messageid + ")"); hboxbb.appendChild(el); el = document.createElement("button"); el.setAttribute("label", "Send"); el.setAttribute("accesskey", "S"); el.setAttribute("oncommand", "su_handle_message_send_command(" + messageid + ")"); hboxbb.appendChild(el); el = document.createElement("button"); el.setAttribute("label", "Cancel"); el.setAttribute("accesskey", "C"); el.setAttribute("oncommand", "su_handle_message_cancel_command(" + messageid + ")"); hboxbb.appendChild(el); box.insertBefore(stack, target_browser); if (url_detail.referral_note) { var measurer = su_get_element("su_bannerTextMeasurer" + messageid); measurer.textContent = url_detail.referral_note + " "; su_set_drawer_open( outerbox_id, true, su_init_message_textbox, messageid); } else { su_set_drawer_open(outerbox_id, true, null); } } function su_init_message_textbox(messageid) { var target_browser = null; var browsers = getBrowser().browsers; for (i = 0; i < browsers.length; i++) { if (browsers[i].su_url_detail && browsers[i].su_url_detail.messageid && (browsers[i].su_url_detail.messageid == messageid)) { target_browser = browsers[i]; break; } } var measurer = target_browser.ownerDocument.getElementById("su_bannerTextMeasurer" + messageid); var height = measurer.boxObject.height; var line_count = Math.round(height / 17); if (line_count > 1) { target_browser.ownerDocument.getElementById("su_bannerLineTextbox" + messageid).hidden = true; var textbox = target_browser.ownerDocument.getElementById("su_bannerMultilineTextbox" + messageid); textbox.setAttribute("rows", line_count - 1); textbox.setAttribute("height", (height + 5) + "px"); textbox.value = target_browser.su_url_detail.referral_note; textbox.hidden = false; } else { var width = measurer.boxObject.width; var textbox = target_browser.ownerDocument.getElementById("su_bannerLineTextbox" + messageid); textbox.setAttribute("width", (width + 10) + "px"); textbox.value = target_browser.su_url_detail.referral_note; textbox.hidden = false; } } function su_get_message_icon_src(url_detail) { var src; if (url_detail.is_friend_referral) { var contact = su_ds.selectRow("contact", "nickname", url_detail.sender); if (! contact) contact = su_ds.selectRow("contact", "contactid", url_detail.sender); if (contact && contact.contactid) { var filename = contact.contactid + ".jpg"; if (su_ds.isResourceInstalled("iconpics", filename)) src = su_ds.getResourceURLFromName("iconpics", filename); else src = "http://cdn.stumble-upon.com/iconpics/" + filename; su_ds.refreshAvatar(contact.contactid); } else { src = "chrome://stumbleupon/content/skin/arrow.png"; } } else if (url_detail.is_system_referral) { src = "chrome://stumbleupon/content/skin/arrow.png"; } else { src = "chrome://stumbleupon/content/skin/bubble3.png"; } return src; } function su_get_message_label(url_detail) { var label = ""; if (url_detail.is_friend_referral || url_detail.is_system_referral) { if (url_detail.referral_note) label += " says:"; else label += " sent you this page"; } else if (url_detail.referral_note) { label += " reviewed saying:"; } return label; } function su_handle_message_sender_click(event, messageid) { var url_detail = su_get_message_url_detail(messageid); var new_tab = true; if (su_ds.getValue("$sender_click_platform")) new_tab = su_new_tab(event); su_set_location( "http://" + url_detail.sender + "." + su_servername + "/", null, new_tab); } function su_handle_message_keypress(event, messageid) { if (event.keyCode != KeyEvent.DOM_VK_RETURN) return; su_send_reply_message(messageid); } function su_handle_message_reply_command(messageid) { su_get_element("su_bannerReplyButton" + messageid).disabled = true; su_get_element("su_messageSendRow" + messageid).hidden = false; setTimeout( function (messageid) { su_get_element("su_messageTextbox" + messageid).focus(); }, 0, messageid); } function su_handle_message_reload_command(messageid) { var browser = su_get_message_browser(messageid); var url_detail = su_get_message_url_detail(messageid); su_set_location( url_detail.url, null, false); } function su_get_message_browser(messageid) { return su_get_element("su_messageOuterBox" + messageid).parentNode.nextSibling; } function su_get_message_url_detail(messageid) { return su_get_message_browser(messageid).su_url_detail; } function su_handle_message_cancel_command(messageid) { su_get_element("su_bannerReplyButton" + messageid).disabled = false; su_get_element("su_messageSendRow" + messageid).hidden = true; } function su_handle_message_send_command(messageid) { su_send_reply_message(messageid); } function su_send_reply_message(messageid) { var url_detail = su_get_message_url_detail(messageid); var note = su_get_element("su_messageTextbox" + messageid).value; note = su_trim(note); if (note == "") { alert("The reply is blank."); return; } var url = su_get_browser_url(); var params = ""; params = su_arp(params, "url", url); params = su_arp(params, "friend", url_detail.sender); params = su_arp(params, "note", note); params = su_arp(params, "referer", su_get_browser_referrer_url()) var cmp_url = su_get_browser_url(null, true); if ((cmp_url.indexOf("http://video." + su_servername + "/#p") == 0) || (cmp_url.indexOf("http://video." + su_servername + "/?p") == 0)) params = su_arp(params, "videoperma", 1); su_post_url_server_async( "referral.php", params, 15000, su_generic_done); var contact = su_ds.selectRow("contact", "nickname", url_detail.sender); if (contact && contact.contactid) su_ds.refreshAvatar(contact.contactid); su_close_message(messageid, true); su_increment_sendto("friend", url_detail.sender); su_register_activity("referral"); var contact = su_ds.selectRow("contact", "nickname", url_detail.sender); if (contact && contact.contactid) su_ds.refreshAvatar(contact.contactid); su_refresh_referral_menu(5); } function su_handle_message_close_command(messageid) { su_close_message(messageid, true); } function su_close_message(messageid, animate) { var id = "su_messageOuterBox" + messageid; var el = su_get_element(id); if (! el) return; if (animate) { su_set_drawer_open( id, false, function () { el.parentNode.removeChild(el); }); } else { el.parentNode.removeChild(el); } } // called upon logout function su_close_all_messages() { var browsers = getBrowser().browsers; var i; var url_detail; for (i = 0; i < browsers.length; i++) { var browser = browsers[i]; if (! browser.su_url_detail) continue; url_detail = browser.su_url_detail; delete browser.su_url_detail; if (! url_detail.messageid) continue; var id = "su_messageOuterBox" + url_detail.messageid; var el = su_get_element(id); if (el) el.parentNode.removeChild(el); } } // [kudos:] This xul-specific sliding code is derived from the // _showNotification method of the Firefox notificationbox widget in // source file mozilla/toolkit/content/widgets/notification.xml. function su_set_drawer_open(id, state, callback, messageid) { var el = su_get_element(id); var height = el.boxObject.height; var steps = 4; var delta = height / steps; var opacity_delta = 1 / steps; if (state) { el.style.removeProperty("position"); el.style.removeProperty("top"); el.style.marginTop = -height + "px"; el.style.opacity = 0; } else { delta = -delta; opacity_delta = -opacity_delta; } var slide = function (callback, messageid) { var done = false; var style = window.getComputedStyle(el, null); var margin = style.getPropertyCSSValue("margin-top"). getFloatValue(CSSPrimitiveValue.CSS_PX); if (delta > 0 && margin + delta >= 0) { el.style.marginTop = "0px"; el.style.opacity = 1; done = true; } else if (delta < 0 && margin + delta <= -height) { el.style.marginTop = -height + "px"; done = true; } else { el.style.marginTop = (margin + delta).toFixed(4) + "px"; el.style.opacity = Number(el.style.opacity) + opacity_delta; } if (done) { clearInterval(su_drawer_timers[id]); delete su_drawer_timers[id]; if (callback) setTimeout(callback, 100, messageid); } } su_drawer_timers[id] = setInterval(slide, 50, callback, messageid); } function su_display_info(info_type, optDomain) { if (! su_host.ff3plus) return; if (! su_ds.getValue("$show_tutorial_info")) return; if ((! su_ds.hasFeature("$info_tutorial")) && (! su_test_info)) return; // display info only if the toolbar is in default position if (su_ds.getValue("@toolbar-position") != "stumbleupon") return; if (! su_ds.getValue("@toolbar-visible")) return; // close the info if we change thru domain if (su_info_spec && optDomain && su_info_spec.domain && (su_info_spec.domain != optDomain)) { su_close_info(); return; } // Show only one info bubble per day. var now_s = su_get_time_s(); var min_interval = 4 * 3600; // 4 hours var time_s = su_ds.getIntValue("$info_time_s"); var spec = new Object(); spec.closed = false; spec.type = info_type; spec.shown_interval_s = 0; spec.shown_time_s = null; switch (info_type) { case "rate": if ((time_s && ((now_s - time_s) < min_interval)) && (! su_test_info)) return; spec.bubble_offset = (su_host.win) ? 0 : 2; spec.leader_offset = (su_host.win) ? -2 : 0; spec.target_id = "su_thumbup"; spec.shown_pref = "$shown_rate_info"; spec.message = "Friendly reminder: If you rate pages as you go, the toolbar learns what you like and delivers more."; break; case "reviews": if ((time_s && ((now_s - time_s) < min_interval)) && (! su_test_info)) return; spec.bubble_offset = 7; spec.leader_offset = 5; spec.target_id = "su_website_info"; spec.shown_pref = "$shown_reviews_info"; spec.message = "Tip: The Reviews button lets you see what other Stumblers think of this site."; break; case "referral": if ((time_s && ((now_s - time_s) < min_interval)) && (! su_test_info)) return; spec.bubble_offset = (su_host.win) ? 0 : 2; spec.leader_offset = (su_host.win) ? -2 : 0; spec.target_id = "su_referral_menu"; spec.shown_pref = "$shown_referral_info"; spec.message = "Tidbit: You can share a good website with friends or any email address."; break; case "thru_domain": if ((time_s && ((now_s - time_s) < min_interval)) && (! su_test_info)) return; spec.bubble_offset = (su_host.win) ? 5 : 7; spec.leader_offset = (su_host.win) ? 3 : 5; spec.domain = optDomain; spec.target_id = "su_mode_domain"; spec.shown_pref = null; if (su_ds.getValue("$shown_thru_domain_info_count")) spec.message = su_ds.lookup("domain:info_message", optDomain); else spec.message = su_ds.lookup("domain:info_message_simple", optDomain); if (! spec.message) spec.message = "Click here to Stumble thru " + su_ds.getThruDomainChannel(optDomain).name + "."; break; case "photo": if ((time_s && ((now_s - time_s) < min_interval)) && (! su_test_info)) return; spec.bubble_offset = (su_host.win) ? 5 : 7; spec.leader_offset = (su_host.win) ? 3 : 5; spec.target_id = "su_mode_photo"; spec.shown_pref = "$shown_photo_info"; spec.message = "Tip: You can discover more of the web's best images in the Photos channel."; break; case "video": break; case "photo_praise": spec.bubble_offset = (su_host.win) ? 5 : 7; spec.leader_offset = (su_host.win) ? 3 : 5; spec.target_id = "su_mode_all"; spec.shown_pref = "$shown_toall_info"; spec.message = "Enjoy the photos! The globe button changes back to the 'All' channel."; su_close_info(); setTimeout(su_refresh_info, 3000); break; case "thru_domain_praise_toall": spec.bubble_offset = (su_host.win) ? 5 : 7; spec.leader_offset = (su_host.win) ? 3 : 5; spec.target_id = "su_mode_all"; spec.shown_pref = "$shown_toall_info"; spec.message = "Have fun with " + su_ds.getThruDomainChannel(optDomain).name + " pages! The globe button changes back to the 'All' channel."; su_close_info(); setTimeout(su_refresh_info, 3000); break; case "thru_domain_praise_tomore": spec.bubble_offset = (su_host.win) ? 0 : 2; spec.leader_offset = (su_host.win) ? -2 : 0; spec.domain = optDomain; spec.target_id = "su_mode_more"; spec.shown_pref = "$shown_tomore_info"; spec.message = null; // overridden su_close_info(); setTimeout(su_refresh_info, 3000); break; default: return; } su_info_spec = spec; su_ds.setValue("#recent_info_spec", spec); try { su_refresh_info(); } catch (e) { su_log_error("REFRESH INFO", e); } } function su_refresh_info() { var toolbar = su_get_element("su_info_toolbar"); if (! su_info_spec) { toolbar.collapsed = true; return; } var spec = su_info_spec; var target_el = su_get_element(spec.target_id); if ((target_el.boxObject.width == 0) || spec.closed) { su_hide_info(); return; } // record the 'shown info' event var i; var found; var first_thru_domain = false; if (spec.shown_pref) { su_ds.setValue(spec.shown_pref, true); } else if (spec.type == "thru_domain") { var domains = su_ds.getValue("$shown_thru_domain_info_list").split(":"); if (domains.length) { found = false; for (i = 0; i < domains.length; i++) { if (domains[i] == spec.domain) found = true; } if (! found) { var count = su_ds.incrementValue("$shown_thru_domain_info_count"); if (count == 1) { su_ds.setValue("$shown_thru_domain_info_list", spec.domain); } else { domains.push(spec.domain); su_ds.setValue("$shown_thru_domain_info_list", domains.join(":")); } } } else { su_ds.incrementValue("$shown_thru_domain_info_count"); su_ds.setValue("$shown_thru_domain_info_list", spec.domain); } } var now_s = su_get_time_s(); su_ds.setValue("$info_time_s", now_s); su_ds.flushPrefs(); spec.shown_time_s = now_s; // If an old container exists, fix the toolbar height to avoid // collapse/reflow upon browser resize. Then nuke the old // container. var container = su_get_element("su_info_container"); if (container) { toolbar.style.height = toolbar.boxObject.height + "px"; toolbar.removeChild(container); } // construct the speech bubble var x = target_el.boxObject.screenX - toolbar.boxObject.screenX + Math.round(target_el.boxObject.width / 2); var el; var vbox; var hbox; var text; var style; var vbox; var content_el; container = document.createElement("hbox"); container.setAttribute("id", "su_info_container"); container.setAttribute("style", "position: absolute; height: 0; width: 0; margin-bottom: 2px;"); toolbar.appendChild(container); var bubble_outerbox = document.createElement("hbox"); style = "position: absolute; left: " + (x + spec.bubble_offset) + "px; top: 1px;"; bubble_outerbox.setAttribute("style", style); container.appendChild(bubble_outerbox); var bubble_midbox = document.createElement("hbox"); bubble_outerbox.appendChild(bubble_midbox); var bubble = document.createElement("hbox"); style = "border-color: rgb(247,182,0); border-style: solid; border-width: 3px; font-weight: normal; font-size: 12pt; color: black; background-color: rgb(255,255,189); -moz-border-radius-topright: 15px; -moz-border-radius-bottomright: 15px; -moz-border-radius-bottomleft: 15px; -moz-border-radius-topleft: 15px; padding-top: 2px; padding-bottom: 2px; padding-left: 15px; padding-right: 12px;"; bubble.setAttribute("id", "su_info_bubble"); bubble.setAttribute("style", style); if (su_host.mac) bubble.setAttribute("class", "su_pinstripe_infoMessage"); else bubble.setAttribute("class", "su_winstripe_infoMessage"); bubble_midbox.appendChild(bubble); vbox = document.createElement("vbox"); bubble_midbox.appendChild(vbox); el = document.createElement("spacer"); el.setAttribute("flex", "1"); vbox.appendChild(el); var optout = document.createElement("checkbox"); optout.setAttribute("label", "Show tips"); optout.setAttribute("checked", su_ds.getValue("$show_tutorial_info")); optout.setAttribute("style", "margin-left: 15px;"); optout.setAttribute("hidden", "true"); optout.setAttribute("oncommand", "su_handle_info_optout_command(this)"); vbox.appendChild(optout); var bubble_hbox = document.createElement("hbox"); bubble.appendChild(bubble_hbox); // construct bubble content switch (spec.type) { case "thru_domain_praise_tomore": vbox = document.createElement("vbox"); vbox.setAttribute("pack", "top"); bubble_hbox.appendChild(vbox); content_el = document.createElement("label"); if (su_host.win) content_el.setAttribute("style", "margin-right: 20px; font-size: 17px;"); else content_el.setAttribute("style", "margin-right: 20px; font-size: 15px;"); vbox.appendChild(content_el); var seq = su_ds.lookup("domain:tomore_favicon_list", spec.domain); if (seq) { text = document.createTextNode("Have fun with " + su_ds.getThruDomainChannel(spec.domain).name + " pages! You can StumbleThru this and other websites "); content_el.appendChild(text); var domains = seq.split(","); for (i = 0; i < domains.length; i++) { hbox = document.createElement("hbox"); hbox.setAttribute("style", "padding-right:4px;"); content_el.appendChild(hbox); if (i == 0) { text = document.createTextNode("("); hbox.appendChild(text); } vbox = document.createElement("vbox"); if (i == 0) vbox.setAttribute("style", "padding-top:2px; padding-left:2px;"); else vbox.setAttribute("style", "padding-top:2px;"); hbox.appendChild(vbox); el = document.createElement("image"); el.setAttribute("width", "16"); el.setAttribute("height", "16"); el.setAttribute("src", su_get_favicon_url(domains[i])); el.setAttribute("tooltiptext", su_ds.getThruDomainChannel(domains[i]).name); vbox.appendChild(el); text = document.createTextNode(","); hbox.appendChild(text); } text = document.createTextNode("etc.) anytime."); content_el.appendChild(text); } else { text = document.createTextNode("You can StumbleThru " + su_ds.getThruDomainChannel(spec.domain).name + " anytime."); content_el.appendChild(text); } vbox = document.createElement("vbox"); vbox.setAttribute("pack", "top"); bubble_hbox.appendChild(vbox); break; default: vbox = document.createElement("vbox"); vbox.setAttribute("pack", "top"); bubble_hbox.appendChild(vbox); content_el = document.createElement("label"); if (su_host.win) content_el.setAttribute("style", "margin-right: 20px; margin-top: 2px; font-size: 17px;"); else content_el.setAttribute("style", "margin-right: 20px; margin-top: 4px; font-size: 15px;"); vbox.appendChild(content_el); text = document.createTextNode(spec.message); content_el.appendChild(text); vbox = document.createElement("vbox"); vbox.setAttribute("pack", "top"); bubble_hbox.appendChild(vbox); break; } el = document.createElement("toolbarbutton"); if (su_host.mac) el.setAttribute("class", "su_pinstripe_messageCloseButton"); else el.setAttribute("class", "su_winstripe_messageCloseButton"); el.setAttribute("style", "margin-top: 4px;"); el.setAttribute("oncommand", "su_handle_close_info_command()"); bubble_hbox.appendChild(el); // If the bubble overflows with window.innerWidth, narrow the label. var toolbox = su_get_element("navigator-toolbox"); var right_edge = (bubble_outerbox.boxObject.screenX - toolbox.boxObject.screenX) + bubble_outerbox.boxObject.width; var width = content_el.boxObject.width; bubble_outerbox.hidden = true; var right_margin_width = window.innerWidth - right_edge; if (right_margin_width < 0) content_el.style.width = (width + right_margin_width) + "px"; else if (right_margin_width > 110) optout.hidden = false; bubble_outerbox.hidden = false; // Add the arrow leader. el = su_create_html_element("img"); if (su_host.win) style = "position: absolute; left: " + (x - Math.round(25 / 2) + spec.leader_offset) + "px; top: -5px; width: 18px; height: 34px"; else style = "position: absolute; left: " + (x - Math.round(25 / 2) + spec.leader_offset) + "px; top: -10px; width: 18px; height: 34px"; el.setAttribute("style", style); if (su_host.win) el.setAttribute("src", "chrome://stumbleupon/content/skin/arrow_green-c.png"); else el.setAttribute("src", "chrome://stumbleupon/content/skin/arrow_green-b.png"); el.setAttribute("onclick", "su_handle_info_leader_click()"); container.appendChild(el); if (right_margin_width <= 110) { // Add the optout2 box. el = su_create_html_element("div"); style = "position: absolute; left: " + (x - Math.round(25 / 2) + spec.leader_offset - 100) + "px; top: " + (bubble_outerbox.boxObject.height - 20) + "px;"; el.setAttribute("style", style) container.appendChild(el); var optout2 = document.createElement("checkbox"); optout2.setAttribute("label", "Show tips"); optout2.setAttribute("checked", su_ds.getValue("$show_tutorial_info")); optout2.setAttribute("oncommand", "su_handle_info_optout_command(this)"); el.appendChild(optout2); } toolbar.style.height = "auto"; toolbar.collapsed = false; } function su_handle_info_leader_click() { su_dispatch_click(document, su_info_spec.target_id); } function su_create_html_element(lowercase_tag_name) { return document.createElementNS("http://www.w3.org/1999/xhtml", "html:" + lowercase_tag_name); } function su_handle_close_info_command() { su_close_info(); } function su_handle_info_optout_command(el) { su_ds.setValue("$show_tutorial_info", el.checked); } function su_hide_info() { if (! su_info_spec) return; var spec = su_info_spec; if (spec.shown_time_s) { spec.shown_interval_s += su_get_time_s() - spec.shown_time_s; spec.shown_time_s = null; } if (spec.shown_interval_s >= 8) su_close_info(); else toolbar.collapsed = true; return; } function su_close_info() { var el = su_get_element("su_info_container"); if (el) el.parentNode.removeChild(el); if (su_info_spec) su_info_spec.closed = true; su_get_element("su_info_toolbar").collapsed = true; } function su_handle_send_dialog_accept(detail) { var url = detail.url; var params = ""; var contact; switch (detail.mode) { case "send": params = su_arp(params, "url", detail.url); params = su_arp(params, "friend", detail.target); params = su_arp(params, "note", detail.message); params = su_arp(params, "referer", detail.referrer_url); if (detail.stumblevideo) params = su_arp(params, "videoperma", 1); su_post_url_server_async( "referral.php", params, 15000, su_generic_done); su_increment_sendto("friend", detail.target); su_register_activity("referral"); contact = su_ds.selectRow("contact", "nickname", detail.target); if (contact && contact.contactid) su_ds.refreshAvatar(contact.contactid); su_refresh_referral_menu(6); break; case "email": params = su_arp(params, "url", detail.url); params = su_arp(params, "recipient", detail.target); params = su_arp(params, "title", detail.title); params = su_arp(params, "note", detail.message); params = su_arp(params, "referer", detail.referrer_url); if (detail.stumblevideo) params = su_arp(params, "videoperma", 1); su_post_url_server_async( "mailit.php", params, 15000, su_generic_done); // We increment here rather than in email_done() because we don't // want the menupopup closing that occurs in // refresh_referral_menu() to occur after a network delay of // indeterminant length by which time the user may already be // attempting to send to someone else. -- JW su_increment_sendto("email", detail.target); su_refresh_referral_menu(7); break; } } // Handler for menitem "Suggest New Interests" function su_suggest() { getBrowser().contentDocument.location = su_serverhttp + "suggest_interests.php"; } // Handler for menuitem "Update Interests" function su_interests() { if (stumbleid == 0) return; // Redirect to interests page var loc = su_serverhttp + "interests.php"; //!!! disabled because it screws up history // if (su_get_browser_url() != loc) getBrowser().contentDocument.location = loc; } // Handler for button "Toolbar Preferences" function su_preferences(opt_initial_tab) { if (stumbleid == 0) return; var detail = new Object(); detail.initial_tab = (opt_initial_tab) ? opt_initial_tab : null; su_unfocus_searchbox(); window.openDialog( "chrome://stumbleupon/content/preferenceDialog.xul", "su_preferences", "chrome,dialog,centerscreen,dependent", detail); } function su_handle_preference_dialog_accept() { var toolbar_position = su_ds.getValue("@toolbar-position"); var toolbar = su_get_element(toolbar_position); if (! toolbar) { su_log_error( "MOVE FAILSAFE3", new Object(), toolbar_position, su_ds.getValue("@position-group")); setTimeout(alert, 50, "The specified toolbar movement cannot be completed.\n\n" + "The default position will be used.\n\n"); su_ds.setValue("@toolbar-position", "stumbleupon"); su_ds.setValue("@position-group", "first"); } try { su_move_toolbar(true, 6); } catch (e) { su_log_error("PREFERENCE MOVE", e, su_ds.getValue("@toolbar-position"), su_ds.getValue("@position-group")); } try { su_refresh_toggle_button(true); } catch (e) { su_log_error("PREFERENCE TOGGLE", e); } var detail = new Object(); detail.from_preference_dialog = true; su_invoke_global_event("configure-toolbar", detail); su_preference_dialog = null; setTimeout(su_verify_toolbar_move, 0, 6); } // called during the global configure-toolbar event and during init // to set labels for top-level toolbar elements function su_init_labels() { var ids; if (su_promo_mode && (stumbleid == 0)) { ids = new Array( "su_thumbup", "su_referral_promo", "su_website_info_promo", "su_sites_promo", "su_video_promo", "su_profile", "su_friends", "su_referral_menu"); } else { ids = new Array( "su_stumble", "su_thumbup", "su_recthumbup", "su_profile", "su_friends", "su_page_feature_prompt", "su_referral_menu", "su_website_info", "su_mode", "su_sponsor", "firstrater", "su_stumble_menu"); } for (var i = 0; i < ids.length; i++) { if (ids[i] == "su_thumbup") { var element = su_get_element("su_thumbup"); if (element.label == element.getAttribute("showlabel2")) su_set_label("su_thumbup", element.getAttribute("showlabel2")); else su_set_label("su_thumbup", null); } else if (ids[i] == "su_recthumbup") { if (stumbleid) su_set_label("su_recthumbup", su_ds.getValue("$dd_rec_label")); } else { su_set_label(ids[i], null); } } } // Handler for button "Invite Friends" function su_invite(event) { // Redirect to home var loc = "find_friends.php"; var params = null; if (su_ds.getValue("@facebook_user")) { loc = su_arp(loc, "pre", "facebook", true); var client_count = su_ds.getValue("@facebook_client_invite_count"); client_count++; su_ds.setValue("@facebook_client_invite_count", client_count); params = su_arp("", "fbclientcount", client_count); params = su_arp(params, "fbsessioncount", su_ds.incrementValue("#find_friends_facebook_count")); if (stumbleid != 0) { var count = su_ds.getValue("$facebook_invite_count"); count++; su_ds.setValue("$facebook_invite_count", count); params = su_arp(params, "fbcount", count); } } if (stumbleid != 0) su_ds.setValue("$shown_find_friends", true); if (su_host.dist) loc = su_arp(loc, "dist", su_host.dist, true); su_set_server_location( loc, params, su_new_tab(event)); } // Handler for button "Upgrade Now" function su_sponsor(extra) { if (stumbleid == 0) return; // Redirect to sponsor page getBrowser().contentDocument.location = su_serverhttp + "sponsors.php" + extra; } // handler for profile tab buttons function su_redir_tab(event, tab) { try { if (su_promo_mode && (stumbleid == 0)) { if (tab == "") tab = "favorites"; su_handle_promo_click(event, tab); return true; } if (su_overflow_popup_open) { var popup = su_get_element("su_overflow_popup"); if ((typeof popup.hidePopup) == "function") popup.hidePopup(); su_unfocus(); } if (stumbleid == 0) return true; su_set_profile_location(tab, su_new_tab(event)); } catch (e) { su_log_error("HANDLE TAB", e); } return true; } // Sends stumble stats to server (urls and dates you've stumbled upon) function su_upload_stumbles() { if (su_ds.getValue("$stumblestats") == "") { return; } var context = new su_AsyncContext(); context.oldStumbleReport = true; context.quiet = true; var params = ""; params = su_arp(params, "urlids", su_ds.getValue("$stumblestats")); params = su_arp(params, "timestamps", su_ds.getValue("$stumbletimes")); params = su_arp(params, "types", su_ds.getValue("$stumbletypes")); params = su_arp(params, "referralids", su_ds.getValue("$stumblereferrals")); params = su_arp(params, "clienttime", su_get_time_s()); params = su_arp(params, "houroffset", Math.floor((new Date()).getTimezoneOffset() / 60)); su_post_url_server_async( "stumbles.php", params, 15000, su_upload_stumbles_done, context); } function su_upload_stumbles_done(res) { var context = res.detail; if (res.status != 200) return; var s = ""; if (typeof(res.responseText) != "undefined") s = res.responseText; if (su_log_communication) su_log("response stumbles.php", s); su_process_commands(s, context); } // Get rid of the stumble queue function clear_stumbles() { stumbles = new Array(); // su_fu.remove(su_prefDir + "stumbleurls"); su_write_file_user("stumbleurls", ""); try { su_prefetcher.clearTargets(); } catch (e) { su_log_error("PREFETCHER 5", e); } } function su_set_inbox_status(icon) { var message_element = su_get_element("su_messages"); var newimage = "chrome://stumbleupon/content/skin/mail" + icon + ".png"; su_set_image("su_messages", newimage); // right now we don't save between sessions if (icon == 2) { su_ds.setValue("$newmessage", true); if ((! su_ds.getValue("$show_messages")) && (! su_new_user)) su_set_visible("su_messages", true); } else { su_set_visible("su_messages", su_ds.getValue("$show_messages")); su_ds.setValue("$newmessage", false); } su_ds.flushPrefs(); } function su_sendto(friend) { if (stumbleid == 0) return; var current_page = su_get_browser_url(); if (current_page.indexOf("about:") == 0) return; su_unfocus_searchbox(); var detail = new Object(); detail.mode = "send"; detail.target = friend; detail.url = current_page; detail.display_url = su_get_browser_url(null, true); detail.stumblevideo = (su_get_stumblevideo_detail() != null); detail.dialog_title = "Send to " + detail.target; detail.show_target = su_host.mac; detail.referrer_url = su_get_browser_referrer_url(); window.openDialog( "chrome://stumbleupon/content/sendDialog.xul", "", "chrome,dialog,centerscreen,dependent", detail); } // called by sendto() and mailit() to increment the sendto count in // sendto_stats function su_increment_sendto(key_type, key) { var contact; var field_name; if (key_type == "friend") field_name = "nickname"; else if (key_type == "email") field_name = "email"; contact = su_ds.selectRow("contact", field_name, key); var new_contact = false; if (! contact) { new_contact = true; contact = new Object() contact[field_name] = key; } if (contact.referral_count) contact.referral_count++; else contact.referral_count = 1; contact.referral_timestamp = (new Date()).getTime(); if (new_contact) su_ds.insertRow("contact", contact); else su_ds.updateRow(contact); su_ds.flushPrefs(); } function su_share_facebook() { var params = ""; params = su_arp(params, "url", su_get_browser_url()); params = su_arp(params, "target", "facebook"); var context = { target: "facebook", share: true }; su_post_url_server_async( "suprshare.php", params, 15000, su_verbose_generic_done, context); } function su_share_twitter() { var params = ""; params = su_arp(params, "url", su_get_browser_url()); params = su_arp(params, "target", "twitter"); var context = { target: "twitter", share: true }; su_post_url_server_async( "suprshare.php", params, 15000, su_verbose_generic_done, context); } function su_append_twitter_facebook_menuitem(menu, has_avatar) { var item = document.createElement("menuitem"); item.setAttribute("label", "Facebook"); item.setAttribute("tooltiptext", "Share on Facebook"); item.setAttribute("oncommand", "su_share_facebook()"); item.setAttribute("image", "chrome://stumbleupon/content/skin/favicon_facebook.gif"); if (has_avatar) item.setAttribute("class", "menuitem-iconic su-iconic-referral"); else item.setAttribute("class", "menuitem-iconic"); menu.appendChild(item); var item = document.createElement("menuitem"); item.setAttribute("label", "Twitter"); item.setAttribute("tooltiptext", "Share on Twitter"); item.setAttribute("oncommand", "su_share_twitter()"); item.setAttribute("image", "chrome://stumbleupon/content/skin/favicon_twitter.gif"); if (has_avatar) item.setAttribute("class", "menuitem-iconic su-iconic-referral"); else item.setAttribute("class", "menuitem-iconic"); menu.appendChild(item); } function su_refresh_referral_menu(from) { su_invoke_global_event("referral-menu-dirty", null, from); if (su_refreshing_referral_menu) return; su_refreshing_referral_menu = true; setTimeout( function (win, from) { win.su_invoke_global_event("update-referral-menu", null, from); }, 1000, window, from); } // utility object for refresh_referral_menu() function su_SendObj(type, contact) { this.type = type; if (type == "friend") this.name = contact.nickname; else if (type == "email") this.name = contact.email; this.count = (contact.referral_count) ? contact.referral_count : 0; this.timestamp = (contact.referral_timestamp) ? contact.referral_timestamp : 0; this.compare_name = this.name.toLowerCase(); this.avatar_url = ""; if (contact.iconpic) { if (su_ds.isResourceInstalled("iconpics", contact.contactid + ".jpg")) this.avatar_url = su_ds.getResourceURLFromName("iconpics", contact.contactid + ".jpg"); } } function su_update_referral_menu() { su_refreshing_referral_menu = false; if (! su_referral_menu_dirty) return; if (su_referral_popup_open) return; setTimeout(su_update_referral_menu2, 0); } function su_update_referral_menu2() { if (su_referral_popup_open) return; su_refreshing_referral_menu = false; su_referral_menu_dirty = false; try { var i, j, ja, count; var menu = su_get_element("su_referral_menu"); // Delete it if it already exists. var el = su_get_element("su_referral_popup"); if (el) el.parentNode.removeChild(el); var referral_popup = document.createElement("menupopup"); var popup; referral_popup.setAttribute("id", "su_referral_popup"); referral_popup.setAttribute("onpopupshowing", "su_handle_popupshowing(event);"); referral_popup.setAttribute("onpopuphidden", "su_handle_popuphidden(event);"); menu.appendChild(referral_popup); if (su_referral_popup_open) { referral_popup.hidePopup(); su_unfocus(); } var has_avatar = false; var has_email = false; var mains = new Array(); var mutuals = new Array(); var emails = new Array(); var virgin_avatar_mutuals = new Array(); var virgin_avatarless_mutuals = new Array(); var virgin_gmails = new Array(); var virgin_emails = new Array(); var contacts = su_ds.selectAllRows("contact"); var i; if (! contacts) return; for (i = 0; i < contacts.length; i++) { var send_obj; if (contacts[i].mutual) { send_obj = new su_SendObj("friend", contacts[i]); mutuals.push(send_obj); if (send_obj.count) { has_avatar = (has_avatar || (send_obj.avatar_url != "")); mains.push(send_obj); } else if (send_obj.avatar_url == "") { virgin_avatarless_mutuals.push(send_obj); } else { virgin_avatar_mutuals.push(send_obj); } } else if (contacts[i].email && (! contacts[i].hidden)) { send_obj = new su_SendObj("email", contacts[i]); emails.push(send_obj); if (send_obj.count) { has_email = true; mains.push(send_obj); } else if (send_obj.compare_name.indexOf("@gmail.com") != -1) { virgin_gmails.push(send_obj); } else { virgin_emails.push(send_obj); } } } emails.sort(function (a, b) { if ( a.compare_name > b.compare_name ) return 1; if ( a.compare_name < b.compare_name ) return -1; return 0; }); mutuals.sort(function (a, b) { if ( a.compare_name > b.compare_name ) return 1; if ( a.compare_name < b.compare_name ) return -1; return 0; }); var sendtos_count_max = su_ds.getValue("$sendtos_menu_depth"); if (mains.length > sendtos_count_max) { // Add and populate the Recent submenu. -- JW mains.sort(function (a, b) { if ( a.timestamp < b.timestamp ) return 1; if ( a.timestamp > b.timestamp ) return -1; return 0; }); menu = document.createElement("menu"); menu.setAttribute("label", "Recent"); menu.setAttribute("tooltiptext", "Recent recipients"); referral_popup.appendChild(menu); popup = document.createElement("menupopup"); menu.appendChild(popup); var recent_count_max = su_ds.getValue("$recent_sendtos_menu_depth"); for (i = 0; (i < mains.length) && (i < recent_count_max); i++) { ja = document.createElement("menuitem"); ja.setAttribute("label", mains[i].name + " (" + mains[i].count + ")"); ja.setAttribute("oncommand", "su_sendto(\"" + mains[i].name + "\");"); ja.setAttribute("tooltiptext", "Send to " + mains[i].name); popup.appendChild(ja); } // separator ja = document.createElement("menuseparator"); referral_popup.appendChild(ja); } virgin_avatar_mutuals.sort(function (a, b) { return ((Math.random() > 0.5) ? 1 : -1); }); virgin_avatarless_mutuals.sort(function (a, b) { return ((Math.random() > 0.5) ? 1 : -1); }); virgin_gmails.sort(function (a, b) { return ((Math.random() > 0.5) ? 1 : -1); }); virgin_emails.sort(function (a, b) { return ((Math.random() > 0.5) ? 1 : -1); }); var gmail_quota = (sendtos_count_max - (mains.length + virgin_avatar_mutuals.length + virgin_avatarless_mutuals.length)) * 0.5; var gmail_quota_i = 0; while ((mains.length < sendtos_count_max) && ((virgin_avatar_mutuals.length > 0) || (virgin_avatarless_mutuals.length > 0) || (virgin_gmails.length > 0) || (virgin_emails.length > 0))) { if (virgin_avatar_mutuals.length > 0) { mains.push(virgin_avatar_mutuals.shift()); has_avatar = true; } else if (virgin_avatarless_mutuals.length > 0) { mains.push(virgin_avatarless_mutuals.shift()); } else if ((gmail_quota_i < gmail_quota) && (virgin_gmails.length > 0)) { mains.push(virgin_gmails.shift()); gmail_quota_i++; has_email = true; } else if (virgin_emails.length > 0) { mains.push(virgin_emails.shift()); has_email = true; } else { mains.push(virgin_gmails.shift()); has_email = true; } } // Sort the main Share menu by decreasing count and increasing // name. -- JW mains.sort(function (a, b) { if ( a.count < b.count ) return 1; if ( a.count > b.count ) return -1; if ( a.compare_name > b.compare_name ) return 1; if ( a.compare_name < b.compare_name ) return -1; return 0; }); var abbr_send_array = new Array(); var abbr_work_array = new Array(); var max_abbr_idx = 0; for (i = 0; (i < mains.length) && (i < sendtos_count_max); i++) { // Build the abbr_send_array, and begin calcuating e-mail // abbreviations. -- JW var item = mains[i]; var at_idx = item.name.indexOf("@"); if (at_idx == -1) { item.abbr_idx = item.name.length - 1; if (item.abbr_idx > max_abbr_idx) { max_abbr_idx = item.abbr_idx; } } else if (at_idx <= 14) { item.abbr_idx = su_truncate_at(item.name, 14); abbr_work_array.push(item); } else { item.abbr_idx = at_idx; abbr_work_array.push(item); } abbr_send_array.push(item); } var j; var item_a, item_b; for (i = 0; i < abbr_work_array.length; i++) { // Eliminate duplicate e-mail abbreviations. -- JW item_a = abbr_work_array[i]; for (j = i + 1; j < abbr_work_array.length; j++) { item_b = abbr_work_array[j]; var common_idx = (item_a.abbr_idx > item_b.abbr_idx) ? item_b.abbr_idx : item_a.abbr_idx; if (common_idx > 3) common_idx -= 2; while ((item_a.name.substring(0, common_idx + 1) == item_b.name.substring(0, common_idx + 1)) && (common_idx <= item_a.name.length) && (common_idx <= item_b.name.length)) common_idx++; item_a.abbr_idx = (common_idx > item_a.abbr_idx) ? common_idx : item_a.abbr_idx; item_a.abbr_idx = su_truncate_at(item_a.name, item_a.abbr_idx); item_b.abbr_idx = (common_idx > item_b.abbr_idx) ? common_idx : item_b.abbr_idx; item_b.abbr_idx = su_truncate_at(item_b.name, item_b.abbr_idx); } if (item_a.abbr_idx > max_abbr_idx) max_abbr_idx = item_a.abbr_idx } // If twitter or fb are supr linked, then add the link at the top. var twitter_facebook_ontop = su_ds.getValue("$twitter_supr_linked") || su_ds.getValue("$facebook_supr_linked"); if (twitter_facebook_ontop) { su_append_twitter_facebook_menuitem(referral_popup, has_avatar); } if (abbr_send_array.length > 0) { // Populate the main Share menu. -- JW var item_count_max = su_ds.getValue("$sendtos_menu_depth"); for (i = 0; i < abbr_send_array.length; i++) { var item = abbr_send_array[i]; ja = document.createElement("menuitem"); var label; if (item.abbr_idx == item.name.length - 1) label = item.name; else label = item.name.substring(0, item.abbr_idx + ((item.count == 0) ? 4 : 1)) + "..."; if (item.count > 0) label += " (" + item.count + ")"; ja.setAttribute("label", label); ja.setAttribute("tooltiptext", "Send to " + item.name); if (item.type == "friend") { ja.setAttribute("oncommand", "su_sendto(\"" + item.name + "\");"); if (item.avatar_url == "") { if (has_email) { ja.setAttribute("image", "chrome://stumbleupon/content/skin/greyman.png"); if (has_avatar) //!!! create larger image ja.setAttribute("class", "menuitem-iconic su-iconic-referral"); else ja.setAttribute("class", "menuitem-iconic"); } } else { ja.setAttribute("image", item.avatar_url); ja.setAttribute("class", "menuitem-iconic su-iconic-referral"); } } else if (item.type == "email") { ja.setAttribute("oncommand", "su_mailit(\"" + item.name + "\");"); if (has_avatar) //!!! create larger image { ja.setAttribute("image", "chrome://stumbleupon/content/skin/arrow.png"); ja.setAttribute("class", "menuitem-iconic su-iconic-referral"); } } referral_popup.appendChild(ja); } } // If twitter or fb are not supr linked, then add the link to the bottom. if (!twitter_facebook_ontop) { su_append_twitter_facebook_menuitem(referral_popup, has_avatar); } ja = document.createElement("menuseparator"); referral_popup.appendChild(ja); if (mutuals.length > 0) { menu = document.createElement("menu"); menu.setAttribute("label", "Stumblers"); menu.setAttribute("tooltiptext", "All of the stumblers you can share with"); referral_popup.appendChild(menu); popup = document.createElement("menupopup"); menu.appendChild(popup); for (i = 0; i < mutuals.length; i++) { ja = document.createElement("menuitem"); if (mutuals[i].count) ja.setAttribute("label", mutuals[i].name + " (" + mutuals[i].count + ")"); else ja.setAttribute("label", mutuals[i].name); ja.setAttribute("oncommand", "su_sendto(\"" + mutuals[i].name + "\");"); ja.setAttribute("tooltiptext", "Send to " + mutuals[i].name); popup.appendChild(ja); } } if (emails.length > 0) { menu = document.createElement("menu"); menu.setAttribute("label", "All Emails"); menu.setAttribute("tooltiptext", "All email addresses"); referral_popup.appendChild(menu); popup = document.createElement("menupopup"); menu.appendChild(popup); menu = document.createElement("menu"); menu.setAttribute("label", "Remove Email"); menu.setAttribute("tooltiptext", "Remove an email address"); popup.appendChild(menu); var remove_popup = document.createElement("menupopup"); menu.appendChild(remove_popup); ja = document.createElement("menuseparator"); popup.appendChild(ja); for (i = 0; i < emails.length; i++) { var name = emails[i].name; ja = document.createElement("menuitem"); if (emails[i].count) ja.setAttribute("label", name + " (" + emails[i].count + ")"); else ja.setAttribute("label", name); ja.setAttribute("tooltiptext", "Send to " + name); ja.setAttribute("oncommand", "su_mailit(\"" + name + "\");"); popup.appendChild(ja); ja = document.createElement("menuitem"); ja.setAttribute("label", name); ja.setAttribute("oncommand", "su_remove_email(\"" + name + "\");"); ja.setAttribute("tooltiptext", "Remove this address"); remove_popup.appendChild(ja); } } ja = document.createElement("menuitem"); ja.setAttribute("label", "New Email Address..."); ja.setAttribute("image", "chrome://stumbleupon/content/skin/arrow.png"); ja.setAttribute("class", "menuitem-iconic"); ja.setAttribute("tooltiptext", "Send to a new e-mail address"); ja.setAttribute("oncommand", 'su_mailit("");'); referral_popup.appendChild(ja); ja = document.createElement("menuseparator"); referral_popup.appendChild(ja); ja = document.createElement("menuitem"); ja.setAttribute("label", "Find people you know..."); ja.setAttribute("class", "menuitem-iconic"); ja.setAttribute("image", "chrome://stumbleupon/content/skin/friend.png"); ja.setAttribute("tooltiptext", "Import contacts from an address book"); ja.setAttribute("onclick", "su_invite(event);"); referral_popup.appendChild(ja); } catch (e) { su_log_error("REFERRAL MENU", e); } } // utility function for update_referral_menu() function su_truncate_at(str, idx) { if (str.length < idx + 6) idx = str.length - 1; return idx; } // This function grabs urls from recommend.php and stores them in stumbleurls (user_cat is either category id of incat stumble or 0) function su_update_url_cache(user_cat, check_referral, callback, context) { try { var res; var postspec = new Object(); var now = su_get_time_s(); if (context.first_of_day) postspec.first_of_day = 1; postspec.houroffset = Math.floor((new Date()).getTimezoneOffset() / 60); if (su_isInt(user_cat)) { postspec.category = user_cat; } else { if (user_cat.indexOf("LANG_") == 0) { postspec.language = user_cat.substr(5); } else if (user_cat.indexOf("TAG_") == 0) { postspec.tag = user_cat.substr(4); } else if (user_cat.indexOf("USERTAG_") == 0) { var chunk = user_cat.substr(8); chunks = chunk.split('_'); var tag = chunks[1]; var profile = chunks[0]; postspec.showfriend = profile; postspec.tag = tag; } else { if (user_cat == "news") postspec.shownews = 1; else if (user_cat == "video") postspec.mode = "video"; else if (user_cat == "friends") postspec.mode = "friends"; else if (user_cat == "wiki") postspec.mode = "wiki"; else postspec.showfriend = user_cat; } } if (check_referral) postspec.check_referral = 1; // if we need to upload_stumbles, do it if (su_ds.getValue("$stumblestats") != "") { postspec.urlids = su_ds.getValue("$stumblestats"); postspec.timestamps = su_ds.getValue("$stumbletimes"); postspec.types = su_ds.getValue("$stumbletypes"); postspec.referralids = su_ds.getValue("$stumblereferrals"); postspec.clienttime = now; context.oldStumbleReport = true; } postspec.recentlyseen = su_ds.getValue("$recently_seen"); postspec.recentlyseen_publicids = su_ds.getValue("$recently_seen_publicids"); postspec.recentlyseen_referralids = su_ds.getValue("$recently_seen_referralids"); var params = su_build_request_param_string(postspec); params = su_append_sync_params(params); if (callback) context.callbacks.push(callback); context.dd_uc_server = su_servername; context.check_referral = check_referral; su_post_url_server_async( "recommend.php", params, su_ds.getValue("@recommend_timeout_ms"), su_update_url_cache_done, context); } catch (e) { su_log_error("RECOMMEND BEGIN", e); } } function su_update_url_cache_done(res) { try { var context = res.detail; var callback = null; var ancestor_callback = null; if (context) { callback = context.callbacks.pop(); ancestor_callback = context.callbacks.pop(); } if (res.aborted) { if (callback) callback("error", ancestor_callback, context); return; } try { if (res.status == 1) { if (callback) callback("error", ancestor_callback, context); return; } } catch (e) {} try { if (res.status != 200) { // Maintenance mode returns 503 with "ERROR xxx" set. // In that case, let the "ERROR" command be handled. var isMaintenanceMode = false; if(res.status == 503) { var commands = res.responseText.split(" "); if(commands.length && (commands[0] == "ERROR")) { // Let it fall through isMaintenanceMode = true; } } if(!isMaintenanceMode) { if (! context.quiet) alert("The stumbleupon.com server is currently down.\nPlease try again, and if you are still having difficulties,\ngo to " + su_base_url + "feedback.php to report the problem\nError : " + res.error + "\nStatus : " + res.status); if (callback) callback("connection error", ancestor_callback, context); return; } } } catch (e) { if (! context.quiet) alert("The stumbleupon.com server is currently down.\nPlease try again, and if you are still having difficulties,\ngo to " + su_base_url + "feedback.php to report the problem.\nError : connection error"); if (callback) callback("connection error", ancestor_callback, context); } var s = ""; if (typeof(res.responseText) != "undefined") s = res.responseText; if (su_log_communication && ((! context.quiet) || su_log_polling)) su_log("response recommend.php", s); // Parse response text var parsed = s.split("\n"); var undelivered_count = 0; var pre_stumbles = new Array(); // temporary variable for storing stumbles if we are checking referrals // Iterate through commands var i; for (i = 0; i < parsed.length; i++) { if (parsed[i] == "") continue; // Parse command structure var command = parsed[i].split(" "); if (command[0] == "") continue; switch(command[0]) { case "ERROR": if (command[1] == "INCORRECT_PASSWORD" && context.quiet) { // auth failed during polling, so poll less frequently // note that iebar signs out when it receives INCORRECT_PASSWORD su_invoke_global_event("logout", null) return; } else if (command[1] == "NO_INTERESTS") { // Redirect to interests page var loc = su_serverhttp + "interests.php"; //!!! disabled because it screws up history // if (su_get_browser_url() != loc) getBrowser().contentDocument.location = loc; if (callback) callback("error", ancestor_callback, context); return; } else if (command[1] == "NO_SITES") { // do nothing } else { if (! context.quiet) su_handle_error(command[1]); if (callback) callback("error", ancestor_callback, context); return; } break; case "URL": pre_stumbles.push(parsed[i].substr(4)); // Check to see if we have a referral if (typeof(command[8]) != "undefined" && command[8] == 4) undelivered_count++; break; default: su_process_command(parsed[i], context, command); break; } } su_ds.flushPrefs(); // save referral count if (context.user_cat == 0) su_ds.setValue("$undelivered_count", undelivered_count); // might as well clear old stumbles, they are old // and there really should only be 1 of them anyway if (!(context.check_referral && undelivered_count == 0)) { clear_stumbles(); } su_update_referred(false); // populate the stumbles array su_load_stumbles(null); // dump the new stumbles onto the end of stumbles for (i = 0; i < pre_stumbles.length; i++) stumbles.push(pre_stumbles[i]); // Now dump the new stumble queue to disk su_save_stumbles(); if (stumbles.length && (su_ds.lookup("userid:uc_logger_flag", stumbleid) || su_ds.getValue("@dd_uc"))) su_ds.setValue("@dd_uc_server", context.dd_uc_server); if (callback) callback("", ancestor_callback, context); } catch (e) { su_log_error("RECOMMEND DONE", e); } } function su_update_referred(disable_animation) { setTimeout(su_update_referred2, 0, disable_animation); } function su_update_referred2(disable_animation) { var undelivered_count = su_ds.getValue("$undelivered_count"); su_set_label("su_referred", undelivered_count); if (su_get_element("su_referred").disabled) return; if (undelivered_count > 0) { su_register_activity("referred"); if (! disable_animation) su_set_attribute("su_referred", "busy", "true"); su_set_visible("su_referred", true); } else { su_set_visible("su_referred", false); } } function su_save_stumbles() { var towrite = ""; for (var ii = 0; ii < stumbles.length; ii++) towrite += stumbles[ii] + "\n"; su_write_file_user("stumbleurls", towrite); } // Saves a rating to the rating history (so we can grey out rating buttons later) function su_store_rating(u, c) { var url_detail = su_ds.lookup("url:url_detail", u) if (url_detail) url_detail.rating = c; // Load rating history (in case the user has rated something in another window) stumblecat = su_read_file_user("stumblerating"); splitcat = stumblecat.split("\n"); for (var i = 0; i < splitcat.length; i++) { if (splitcat[i] == "") continue; split2 = splitcat[i].split(" "); su_ratings[split2[0]] = split2[1]; } // Add the new rating su_ratings[u] = c; // Now dump it to disk var towrite = ""; for (var ii in su_ratings) { if (su_is_property_garbage(su_ratings, ii)) continue; towrite += ii + " " + su_ratings[ii] + "\n"; } su_write_file_user("stumblerating", towrite); } function su_delete_rating(u) { var url_detail = su_ds.lookup("url:url_detail", u) if (url_detail) url_detail.rating = null; // Load rating history (in case the user has rated something in another window) stumblecat = su_read_file_user("stumblerating"); splitcat = stumblecat.split("\n"); su_ratings = new Array(); for (var i = 0; i < splitcat.length; i++) { if (splitcat[i] == "") continue; split2 = splitcat[i].split(" "); if (split2[0] != u) su_ratings[split2[0]] = split2[1]; } // Now dump it to disk var towrite = ""; for (var ii in su_ratings) { if (su_is_property_garbage(su_ratings, ii)) continue; towrite += ii + " " + su_ratings[ii] + "\n"; } su_write_file_user("stumblerating", towrite); } // performs a synchronous POST, when the interface is beneath the www // stumbleupon domain function su_post_url_server(uri_suffix, postdata) { return su_post_url( su_serverhttp + uri_suffix + "?username=" + stumbleid, postdata); } function su_post_url_server_secure(uri_suffix, postdata) { return su_post_url( su_serverhttps + uri_suffix + "?username=" + stumbleid, postdata); } // performs a synchronous POST function su_post_url(uri, postdata) { var script_timeout_saved; try { if (su_ds.isPrefDefined("dom.max_chrome_script_run_time")) { script_timeout_saved = su_ds.getValue("dom.max_chrome_script_run_time"); su_ds.setValue("dom.max_chrome_script_run_time", 120); } } catch (e) {} // This function trys to post 3 times (since there is // something screwy with xmlhttprequest). var ret2 = new Object(); var x; var status; var retries = 3; if (! postdata) postdata = ""; var client_postdata = su_get_client_postdata(uri); if (client_postdata != "") postdata += ((postdata == "") ? "" : "&") + client_postdata; for (var i = 1; i <= retries; i++) { x = new XMLHttpRequest(); netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead"); x.open("POST", uri, false); // x.setRequestHeader("User-Agent" , su_useragent); // unnecessary since we set X-SU-Version x.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); try { if (su_log_communication && (uri.indexOf("topics.csv") == -1)) su_log("post sync", uri, postdata, "attempt: " + i); x.send(postdata); status = x.status; break; } catch (e) { if (i == retries) { // Failed on 3nd try, bail out ret2.error = e; ret2.response = ""; ret2.status = 1; try { if (su_ds.isPrefDefined("dom.max_chrome_script_run_time")) { su_ds.setValue( "dom.max_chrome_script_run_time", script_timeout_saved); } } catch (e) {} return ret2; } } } ret2.error = ""; ret2.response = x.responseText; if (typeof(ret2.response) == "undefined") ret2.response = ""; ret2.status = x.status; var mime = ''; try { mime = x.getResponseHeader("Content-Type"); } catch (e) { mime = ''; } if (mime != null && typeof(mime) != "undefined" && mime != '') { var mimes = mime.split(";"); ret2.mimetype = mimes[0]; } else ret2.mimetype = ''; try { if (su_ds.isPrefDefined("dom.max_chrome_script_run_time")) { su_ds.setValue( "dom.max_chrome_script_run_time", script_timeout_saved); } } catch (e) {} return ret2; } // begins an asynchronous POST, when the interface is beneath the www // stumbleupon domain function su_post_url_server_async(uri_suffix, postdata, timeout_interval_ms, callback, detail) { if (! detail) detail = new Object(); detail.request_target = uri_suffix; su_post_url_async( su_serverhttp + uri_suffix + ((stumbleid && (uri_suffix != "stumblethru.csv")) ? ("?username=" + stumbleid) : ""), postdata, timeout_interval_ms, callback, detail); } function su_post_url_server_async_secure(uri_suffix, postdata, timeout_interval_ms, callback, detail) { if (! detail) detail = new Object(); detail.request_target = uri_suffix; su_post_url_async( su_serverhttps + uri_suffix + ((stumbleid && (uri_suffix != "stumblethru.csv")) ? ("?username=" + stumbleid) : ""), postdata, timeout_interval_ms, callback, detail); } // begins an asynchronous POST function su_post_url_async(uri, postdata, timeout_interval_ms, callback, detail) { // This ensures that our request objects are created in the context // of this window. This is necessary for the first stumble after // new account creation. -- JW setTimeout(function (window, uri, postdata, timeout_interval_ms, callback, detail) { window.su_post_url_async_wrapped(uri, postdata, timeout_interval_ms, callback, detail); }, 0, window, uri, postdata, timeout_interval_ms, callback, detail); } // do not call this; call post_url_async instead function su_post_url_async_wrapped(uri, postdata, timeout_interval_ms, callback, detail) { if (! postdata) postdata = ""; postdata += ((postdata == "") ? "" : "&") + su_get_client_postdata(uri); su_service.postAsync(su_useragent, uri, postdata, timeout_interval_ms, callback, detail); } // Used by post_url, post_url_async and stumble_done to // construct version and authentication portions of postdata function su_get_client_postdata(uri) { var postdata = ""; if (uri.indexOf(su_serverhttp) == 0) postdata += "version=" + su_verstring; if (su_is_auth_allowed(uri)) { if (su_enable_hashed_password) { postdata += ((postdata == "") ? "" : "&") + "username=" + stumbleid + "&password=" + stumblepass + "&ycc=" + su_ds.getCC(); } else { postdata += ((postdata == "") ? "" : "&") + "username=" + stumbleid + "&password=" + encodeURIComponent(stumblepass) + "&ycc=" + su_ds.getCC(); } } return postdata; } // used by the http_observer and get_client_postdata to determine // whether we're allowed to send authentication to the page function su_is_auth_allowed(url) { if (! su_is_matching_domain(url, su_servername)) return false; if ((url.indexOf(su_serverhttp == 0)) || (url.indexOf(su_serverhttps == 0))) { // These get special authentication sent in postdata. if ((su_is_server_page(url, "userexists.php")) || (su_is_server_page(url, "delete_account.php")) || (su_is_server_page(url, "change_password.php")) || (su_is_server_page(url, "sign_up.php")) || (su_is_server_page(url, "getid.php")) || (su_is_server_page(url, "init_user.php")) || (su_is_server_page(url, "signup.php"))) return false; // Don't bother with obvious non-pages.... if ((su_is_server_page(url, "images/")) || (su_is_server_page(url, "pics/")) || (su_is_server_page(url, "iconpics/")) || (su_is_server_page(url, "superminipics/")) || (su_is_server_page(url, "groupsuperminipics/")) || (su_is_server_page(url, "topicsuperminipics/")) || (su_is_server_page(url, "mediumpics/")) || (su_is_server_page(url, "thumb/")) || (su_is_server_page(url, "css/")) || (su_is_server_page(url, "js/")) || (su_is_server_page(url, "favicon.ico")) || (su_is_server_page(url, "stumble.js")) || (su_is_server_page(url, "post.js")) || (su_is_server_page(url, "help.js"))) return false; } return true; } function su_handle_page_feature_prompt_click(event) { var url = su_get_browser_url(); var search_service_id = su_get_service_id(url, true); if (su_is_matching_domain(url, "facebook.com")) { if (su_ds.getValue("$facebook_added")) { su_ds.setValue("$facebook_linked", true); su_set_server_location( "facebook/index.php?link", null, su_new_tab(event)); } else { su_set_location( "http://apps.facebook.com/stumbleupon/", null, su_new_tab(event)); } } else if (search_service_id) { su_ds.setValue("$show_searchlinks_score", true); su_ds.setValue("$show_searchlinks_friends", true); su_ds.setValue("$shown_searchlinks", true); if (su_new_tab(event)) { su_set_location(url, null, true); } else { su_search_results_page( getBrowser().contentDocument, search_service_id); } } su_set_visible("su_page_feature_prompt", false); } // handles the click event for the website_info button function su_handle_website_info_click(event) { // button is disabled if (su_get_element("su_website_info").getAttribute("image") == "chrome://stumbleupon/content/skin/bubblex.png") return; su_website_info(su_new_tab(event), "", 0); } function su_handle_website_info_promo_click(event, from_control_id) { if (su_search_service_id) { su_handle_promo_click(event, "search"); return; } // button is disabled if (su_get_element("su_website_info_promo").disabled) return; var url = su_get_browser_url(); var cmp_url = url.toLowerCase(); if (cmp_url.indexOf("http://video." + su_servername + "/#p") == 0) return; if (cmp_url.indexOf("http://video." + su_servername + "/?p") == 0) return; var loc; var params = null; if (url.indexOf("about:") == 0) { su_verify_cookie_perms(false); loc = "sign_up.php"; if (su_ds.getValue("@facebook_user")) loc = su_arp(loc, "pre", "facebook", true); loc = su_arp(loc, "pre2", from_control_id, true); if (su_host.dist) loc = su_arp(loc, "dist", su_host.dist, true); } else { loc = "url/" + su_review_url(url); params = ""; if (su_ds.getValue("@facebook_user")) params = su_arp(params, "pre", "facebook"); params = su_arp(params, "pre2", from_control_id); if (su_host.dist) params = su_arp(params, "dist", su_host.dist); params = su_arp(params, "retry_url", url); } su_set_server_location( loc, params, su_new_tab(event)); } function su_handle_promo_click(event, from_control_id) { var is_search = false; var url = su_get_browser_url(); var detail = new Object(); if (from_control_id == "search") { is_search = true; from_control_id = su_search_service_id; detail = su_get_search_query_detail(su_search_service_id, url); } su_verify_cookie_perms(false); var loc = "sign_up.php"; var params = null; if (su_ds.getValue("@facebook_user")) loc = su_arp(loc, "pre", "facebook", true); loc = su_arp(loc, "pre2", from_control_id, true); if (su_host.dist) loc = su_arp(loc, "dist", su_host.dist, true); if (detail.is_short_query_results) params = su_arp("", "post_url", url); else if (detail.is_query_results) params = su_arp("", "post_url2", url); else if (from_control_id == "referral") loc = su_arp(loc, "url", url, true); su_set_server_location( loc, params, su_new_tab(event)); } function su_handle_video_promo_click(event) { su_get_element("su_stumble").image="chrome://stumbleupon/content/skin/stumble2.png"; su_stumble_action_count++; setTimeout( su_reset_stumble_action_indicator, su_ds.getValue("@stumble_action_timeout_ms"), su_stumble_action_count); su_stumble_video(su_new_tab(event)); } function su_handle_tag_command(force_dialog) { var searchbox = su_get_element("su_searchbox"); if (searchbox.open) searchbox.closePopup(); setTimeout(su_handle_tag_command2, 0, force_dialog); } function su_get_title(opt_doc, opt_raw_url) { var doc = (opt_doc) ? opt_doc : getBrowser().contentDocument; if (doc.title != "") return doc.title; if (opt_raw_url) return opt_raw_url; return su_get_browser_url(doc, true) } function su_handle_tag_command2(force_dialog) { //!!! canonize tag? var current_url = su_get_browser_url(); if (su_url_has_tag) { var tag = su_get_tag_list(current_url); if (tag) { su_tagit(current_url, tag, true, su_get_title(), su_get_browser_url(null, true)); return; } } su_unfocus_searchbox(); // see if searchbox is hidden var tag = ''; if (force_dialog || (su_get_element("su_field").collapsed == true)) { var detail = new Object(); detail.url = current_url; detail.tags_default = su_get_element("su_searchbox").value; if (detail.tags_default == su_tag_instructions) detail.tags_default = ""; window.openDialog( "chrome://stumbleupon/content/taggingDialog.xul", "", "chrome,dialog,centerscreen,dependent", detail); } else { tag = su_get_element("su_searchbox").value; if (tag == su_tag_instructions) tag = ""; if (tag == "") { // put a little instruction thing up var alerttext = "To tag a page, type some tags into the text box before clicking the tag button.\nTags are descriptive keywords you can use to organize and share useful websites.\nTags may contain spaces, letters, and numbers and must be separated by commas.\nFor example, you might tag page of travel photos as \"photos, traveling, costa rica\".\n\nYou can lookup sites you've tagged using the 'Find pages you liked' button on your Favorites page."; alert(alerttext); // put focus in search box su_get_element("su_searchbox").focus(); return; } var tagerror = su_validate_tagstring(tag); if (tagerror != null) { alert(tagerror); return; } su_tagit(current_url, tag, false, su_get_title(), su_get_browser_url(null, true)); } } function su_validate_tagstring(str) { // validate tag... var tags = str.split(','); var tagerror = null; // Itetag through commands var tagcount = 0; for (var i = 0; i < tags.length; i++) { if (tags[i] == "") continue; tagcount++; if (tagcount > 5) { tagerror = 'You cannot apply more than 5 tags to a page.'; break; } var thetag = tags[i]; if (thetag.indexOf('http://') != -1) { tagerror = 'If you want to search for a site, enter some search terms then click \'enter\'.\nTo tag a page, type in some keywords before clicking this icon.'; break; } if (thetag.length > 32) { tagerror = 'Each tag cannot be longer than 32 characters.\nYour tag \'' + thetag + '\' is ' + thetag.length + ' characters long.'; break; } var tagpieces = thetag.split(/[^A-Za-z0-9]/); // alert(tagpieces.length); var tagpiececount = 0; for (var j = 0; j < tagpieces.length; j++) { if (tagpieces[j] == "") continue; //alert(tagpieces[j]); tagpiececount++; if (tagpiececount > 3) { tagerror = 'Each tag cannot have more than 3 words. For example,\n \'costa rica trip\' is a valid tag, but \'costa rica trip photos\' is not.\nYour tag \'' + thetag + '\' has ' + tagpiececount + ' words.'; break; } } if (tagpiececount > 3) break; } return tagerror; } function su_tagit(url, tag, untag, opt_title, opt_raw_url) { // when you tag, we know it's not a tag on i-likeit su_last_typed_tag = 0; if ((url == "") || (url.indexOf("about:") == 0)) return; var context = new su_AsyncContext(); context.url = url; context.tag = tag; context.ref_url = (opt_raw_url) ? opt_raw_url : su_get_browser_url(null, true); context.untagging = untag; if (! untag) context.title = (opt_title) ? opt_title : su_get_title(); var params = "tag=" + escape(tag) + "&url=" + encodeURIComponent(url); params = su_arp(params, "referer", su_get_browser_referrer_url()); params = su_append_sync_params(params); if (untag) { // we want to undo this tag su_post_url_server_async( "untagit.php", params, null, su_untag_done, context); } else { su_post_url_server_async( "tagit.php", params, null, su_tag_done, context); } return; } function su_untag_done(res) { try { if (res.status == 1) return; } catch (e) { return; } if (res.status != 200) { su_http_error(res.error, res.status); return; } var context = res.detail; // success! // !!! go to info page? (middle click or option?) var s = ""; if (typeof(res.responseText) != "undefined") s = res.responseText; if (su_log_communication) su_log("response untagit.php", s); su_process_commands(s, context); if (context.error) return; su_load_tags(context.url); su_store_tags(); su_enable_tag_toolbar(); return; } function su_tag_done(res) { try { if (res.status == 1) return; } catch (e) { return; } if (res.status != 200) { su_http_error(res.error, res.status); return; } var context = res.detail; // success! // !!! go to info page? (middle click or option?) var s = ""; if (typeof(res.responseText) != "undefined") s = res.responseText; if (su_log_communication) su_log("response tagit.php", s); su_process_commands(s, context); if (context.error) return; var tag = su_normalize_tag(context.tag); su_load_tags(context.url); // Add the new tag var o = new Object(); o.url = context.url; o.tag_list = tag; su_tag_lists_by_url[context.url] = tag; su_tags.unshift(o); su_store_tags(); su_disable_tag_toolbar(tag); su_old_search = tag; su_get_element("su_tag").image="chrome://stumbleupon/content/skin/tag2.png"; su_get_element("su_tag2").image="chrome://stumbleupon/content/skin/tag2.png"; } // Returns the size of the URL in bytes; must be cached and therefore an HTTP or FTP URL function su_get_size(url) { var cacheService = su_get_service( "@mozilla.org/network/cache-service;1", "nsICacheService"); var httpCacheSession = cacheService.createSession("HTTP", 0, true); httpCacheSession.doomEntriesIfExpired = false; var ftpCacheSession = cacheService.createSession("FTP", 0, true); ftpCacheSession.doomEntriesIfExpired = false; try { var cacheEntryDescriptor = httpCacheSession.openCacheEntry(url, Components.interfaces.nsICache.ACCESS_READ, false); if (cacheEntryDescriptor) return cacheEntryDescriptor.dataSize; } catch(ex) {} try { cacheEntryDescriptor = ftpCacheSession.openCacheEntry(url, Components.interfaces.nsICache.ACCESS_READ, false); if (cacheEntryDescriptor) return cacheEntryDescriptor.dataSize; } catch(ex) {} return -1; } // Handler for photoblog function su_blogImage(rating) { su_photoblogimage = document.popupNode; if (su_get_size(su_photoblogimage.src) > 250000) { su_photoblogimage = null; alert("Image too large (250kb max size)"); return; } if (su_photoblogimage.width > 715) { su_photoblogimage = null; alert("Image too large (715px max width)"); return; } if (su_photoblogimage.height > 715) { su_photoblogimage = null; alert("Image too large (715px max height)"); return; } /* // see if we need to grab the referring page for this image var current_page = su_get_browser_url(); alert("currente page: " + current_page + " su_photoblogimage: " + su_photoblogimage.src); if (current_page == su_photoblogimage.src) { // we want to find the referring page... var referer = getBrowser().contentDocument.referrer; alert("referer " + referer); if (typeof(referer) != "undefined" && referer != null && referer != "" && referer.indexOf('http://') != -1) { // we need to rate the referering page.. alert("refering page: " + referer); return; } } alert("no referring page"); return; */ // first do rating... su_rate(rating, false, true, false, 0); } // pre-Handler for button "rate" function su_handle_rate_click(event, r) { if (su_promo_mode && (stumbleid == 0) && (! su_get_stumblevideo_detail())) { if (r > 0) su_handle_website_info_promo_click(event, "thumbup"); else su_handle_website_info_promo_click(event, "thumbdown"); return; } if (r == 2) { r = 1; su_d_rec_rating = true; } else { su_d_rec_rating = false; } var url = su_get_browser_url(); var old_rating = su_get_rating(url, (su_get_stumblevideo_detail() != null)); // see if they are unrating an old rating if ((old_rating != null) && ((old_rating == r) || (r == 0 && (old_rating <= 0)))) { setTimeout(su_unrate, 0); return; } if (su_get_element("su_thumbup").disabled == true) return; if (typeof(event.button) == "undefined") event.button = 0; // For menu entries, simulate left button var platform_ctrl_key = (su_host.mac) ? event.metaKey : event.ctrlKey; if (((event.button == 0) && (! platform_ctrl_key)) && (! su_ds.getValue("$rate_new_window"))) su_rate(r, false, false, false, 0); else if ((event.button == 1) || ((event.button == 0) && platform_ctrl_key) || su_ds.getValue("$rate_new_window")) su_rate(r, true, false, false, 0); } // Handler for button "rate" function su_unrate() { su_check_progress_listener(); if ((stumbleid == 0) && (! su_promo_mode)) return; var theurl = su_get_browser_url(); if (stumbled_redirect != '' && theurl == stumbled_redirect) { // we have a redirect, rate the original url we stumbled on theurl = stumbled_url; } var sv_detail = su_get_stumblevideo_detail(); if (sv_detail) { var doc = getBrowser().contentDocument; su_stumblevideo_toolbar_rate = true; var thumbup = doc.getElementById("thumbUp"); var thumbdown = doc.getElementById("thumbDown"); if (thumbup.src.indexOf("_sel") != -1) su_dispatch_click(doc, "thumbUp"); else if (thumbdown.src.indexOf("_sel") != -1) su_dispatch_click(doc, "thumbDown"); return; } // grey out the buttons until the rating goes through su_get_element("su_thumbup").disabled=true; su_get_element("su_thumbdown").disabled=true; su_get_element("su_thumbup").setAttribute("onclick", ""); var params = ""; params = su_arp(params, "url", theurl); params = su_append_sync_params(params); var context = new su_AsyncContext(); context.url = theurl; context.ref_url = context.url; su_post_url_server_async( "unrate.php", params, null, su_unrate_done, context); su_check_progress_listener(); } function su_unrate_done(res) { try { if (res.status == 1) { su_enable_toolbar(); return; } } catch (e) { return; } if (res.status != 200) { su_http_error(res.error, res.status); su_enable_toolbar(); return; } var context = res.detail; context.unrating = true; var s = ""; if (typeof(res.responseText) != "undefined") s = res.responseText; if (su_log_communication) su_log("response unrate.php", s); su_process_commands(s, context); if (context.error && !context.discoveryCancelled) { su_enable_toolbar(); return; } // Store in list of rated urls su_delete_rating(context.url); su_refresh_pagemeta(false, 3); su_check_progress_listener(); } // Handler for button "rate" function su_block_domain() { var url = su_get_browser_url(); var rating = su_get_rating(url, (su_get_stumblevideo_detail() != null)); var domain = su_get_tld(url); var blk_domain = su_is_domain_blocked(domain) ? -1 : 1; if (rating == null && blk_domain == 1) rating = -2; if (rating == null && blk_domain == -1) { var context = new su_AsyncContext(); context.url = url; context.ref_url = url; var params = ""; params = su_arp(params, "url", url); params = su_arp(params, "blkdomain", -1); params = su_append_sync_params(params); su_post_url_server_async( "unrate.php", params, null, su_unrate_done, context); } else { su_rate(rating, false, true, false, blk_domain, url); } } // Handler for button "rate" function su_rate(r, open_reviews, force_nostumble, force_comment, blk_domain, opt_url) { su_register_activity("rate"); su_check_progress_listener(); try { su_close_info(); } catch (e) {} // If we are opening a comment button in a new tab // we shouldn't be stumbling if (open_reviews) force_nostumble = true; if ((stumbleid == 0) && (! su_promo_mode)) return; var rating = r; var theurl = (opt_url) ? opt_url : su_get_browser_url(); // su_dd("rate", theurl, stumbled_redirect); // return; if (stumbled_redirect != '' && theurl == stumbled_redirect) { // we have a redirect, rate the original url we stumbled on theurl = stumbled_url; } if (rating > 0) { // We try to keep our own local thumbup count but defer to the server when it sends an // SFC command su_ds.incrementValue("$thumbup_count"); su_thumbup_count_changed(); } else su_ds.incrementValue("$thumbdown_count"); var sv_detail = su_get_stumblevideo_detail(); if (sv_detail && (! ((su_ds.getValue("$bad_stumble", false) && rating <= 0) || (su_ds.getValue("$great_stumble", false) && rating == 1)))) { var doc = getBrowser().contentDocument; su_stumblevideo_toolbar_rate = true; if (rating == 1) su_dispatch_click(doc, "thumbUp"); else if (rating <= 0) su_dispatch_click(doc, "thumbDown"); return; } else if (sv_detail) { theurl = sv_detail.url; } var cmp_url = theurl.toLowerCase(); if (cmp_url.indexOf("http://video." + su_servername + "/#p") == 0) return; if (cmp_url.indexOf("http://video." + su_servername + "/?p") == 0) return; // grey out the buttons until the rating goes through su_get_element("su_thumbup").disabled=true; su_get_element("su_thumbdown").disabled=true; su_get_element("su_thumbup").setAttribute("onclick", ""); su_quote = ""; if (getBrowser().contentWindow.getSelection) su_quote = getBrowser().contentWindow.getSelection().toString(); var charset = ""; var webShell = getBrowser().docShell.QueryInterface(Components.interfaces.nsIDocCharset); if (webShell) charset = webShell.charset; var doc = getBrowser().contentDocument; var context = new su_AsyncContext(); context.rating = rating; context.url = theurl; context.ref_url = su_get_browser_url(doc, true); context.browser = getBrowser().selectedBrowser; context.title = su_get_title(doc, context.ref_url); context.force_nostumble = force_nostumble; context.force_comment = force_comment; context.timestamp = (new Date()).getTime(); context.open_reviews = open_reviews; context.charset = charset; context.referrer = doc.referrer; context.stumblevideo_mode = null; context.blk_domain = blk_domain; var postdata = "rating=" + rating + '&url=' + encodeURIComponent(theurl) + "&charset=" + encodeURIComponent(charset) + "&referer=" + encodeURIComponent(context.referrer) + "&blkdomain=" + blk_domain; if (sv_detail) postdata += "&videoperma=1"; postdata = su_append_sync_params(postdata); su_post_url_server_async( "rate.php", postdata, null, su_rate_done, context); su_check_progress_listener(); } function su_rate_done(res) { try { if (res.status == 1) { su_enable_toolbar(); return; } } catch (e) { return; } if (res.status != 200) { su_http_error(res.error, res.status); su_enable_toolbar(); return; } var context = res.detail; if (context.browser == getBrowser().selectedBrowser) { if ((context.stumblevideo_mode == "page") || (! su_ds.getValue("$bad_stumble") && (context.rating <= 0)) || (! su_ds.getValue("$great_stumble") && (context.rating == 1))) su_disable_toolbar(context.rating); } var s = ""; if (typeof(res.responseText) != "undefined") s = res.responseText; if (su_log_communication) su_log("response rate.php", s); // Parse response text var parsed = s.split("\n"); var prepend = ""; var discovery = false; var firstrate = 0; var canceled = false; // Iterate through commands for (var i = 0; i < parsed.length; i++) { if (parsed[i] == "") continue; // Parse command structure var command = parsed[i].split(" "); switch(command[0]) { case "URL": prepend += command[1] + "\n"; break; case "FIRSTRATER": firstrate = command[1]; break; case "NEWURL" : // do 800x600+ if (context.rating == 1) { discovery = true; su_disable_toolbar(context.rating); var detail = new Object(); detail.finalized = false; detail.submitted = false; detail.url = context.url; detail.uri_suffix = "newurl.php"; detail.tagtext = ""; detail.postdata = "url=" + encodeURIComponent(context.url) + "&title=" + encodeURIComponent(context.title) + "&charset=" + encodeURIComponent(context.charset) + "&rating=" + context.rating + ""e=" + encodeURIComponent(su_quote) + "&referer=" + encodeURIComponent(context.referrer) + "&catidlist=" + encodeURIComponent(''); if (su_photoblogimage) { detail.postdata += "&image=" + encodeURIComponent(su_photoblogimage.src) + "&width=" + su_photoblogimage.width + "&height=" + su_photoblogimage.height; su_photoblogimage = null; } var width = (command.length >= 2) ? parseInt(command[1]) : 700; var height = (command.length >= 3) ? parseInt(command[2]) : 450; var dialog_url = "chrome://stumbleupon/content/discoveryDialog.xul"; dialog_url += "#d" + su_ds.incrementValue("~discovery_count"); su_ds.define("disc_dialog_url:disc_detail", dialog_url, detail); su_ds.addEventListener( "discdlgclose", function (event) { window.su_handle_discovery_dialog_close(event); }); window.openDialog( dialog_url, "", "chrome,dialog,centerscreen,width=" + width + ",height=" + height + ",resizable=1", detail); // calculate this before we get the add comment var da = new Date(); var now = da.getTime(); // Store in list of rated urls su_store_rating(context.url, (su_d_rec_rating) ? 2 : context.rating); } else if ((context.rating <= 0) && (context.browser == getBrowser().selectedBrowser)) { var tmpres = new Object(); tmpres.detail = new su_AsyncContext(); tmpres.detail.url = context.url; tmpres.status = 200; tmpres.responseText = ""; su_unrate_done(tmpres); canceled = true; if (context.blk_domain == 0) setTimeout(su_show_thumbdown_discovery_alert, 0); } var time_between_tagging = now - su_last_typed_tag; var i_just_stumbled = false; return; default: su_process_command(parsed[i], context, command); if (context.error) { su_enable_toolbar(); return; } break; } } setTimeout(su_refresh_pagemeta, 0, false, 9); if (canceled) return; if ((context.rating == 1) && (! discovery)) { if (! su_ds.getValue("$shown_reviews_info")) su_display_info("reviews"); else if (! su_ds.getValue("$shown_referral_info")) su_display_info("referral"); } // Store in list of rated urls su_store_rating(context.url, (su_d_rec_rating) ? 2 : context.rating); // Prepend URLs if we got any if (prepend != "") { prior = su_read_file_user("stumbleurls"); su_write_file_user("stumbleurls", prepend + prior); } var searchbox_value = su_get_element("su_searchbox").value; if ((! su_ds.getValue("$show_field")) || (searchbox_value == su_tag_instructions)) searchbox_value = ""; // calculate this before we get the add comment var now = (new Date()).getTime(); var time_between_tagging = now - su_last_typed_tag; var opened_website_info = false; if (su_photoblogimage) { opened_website_info = true; su_website_info(false, context.url, firstrate); } // else if (context.force_comment || ((! context.open_reviews) && // su_ds.getValue("$comment_firstrating") && firstrate != 0)) // { // su_unfocus_searchbox(); // // window.openDialog( // "chrome://stumbleupon/content/ratingDialog.xul", // "StumbleUpon Review", // "chrome,modal,dialog,centerscreen,dependent", // context.url, // firstrate, // searchbox_value, // su_quote); // } var tag_term = su_get_element('su_searchbox').value; // if they've typed a tag in within the last 10 seconds, tag it if (context.rating == 1 && tag_term != '' && su_last_typed_tag != 0 && time_between_tagging < 1000 * 6) { su_tagit(context.url, tag_term, false, context.title, context.ref_url); // clear it once we are done.. su_last_typed_tag = 0; su_old_search = ''; //su_get_element('su_searchbox').value = ''; } var i_just_stumbled = false; // Stumble-On-Rate if ( (! context.force_nostumble) && ((su_ds.getValue("$bad_stumble") && context.rating <= 0) || (su_ds.getValue("$great_stumble") && context.rating == 1)) ) { stumble(0); i_just_stumbled = true; } if ((! opened_website_info) && (! i_just_stumbled) && context.open_reviews && (context.rating == 1) && (context.stumblevideo_mode != "page")) { su_website_info(0, context.url, 0); } su_check_progress_listener(); } function su_prepare_thumbdown_menu() { var url = su_get_browser_url(); var rating = su_get_rating(url, (su_get_stumblevideo_detail() != null)); // Handle checks su_get_element('su_thumbdown_menu_notforme').setAttribute("checked", ((rating == -2) || (rating == 0))); su_get_element('su_thumbdown_menu_spam').setAttribute("checked", (rating == -5)); su_get_element('su_thumbdown_menu_dupe').setAttribute("checked", (rating == -3)); // su_get_element('su_thumbdown_menu_saturation').setAttribute("checked", (rating == -4)); if (! su_host.places) { su_get_element('su_thumbdown_menu_blockdomain').hidden = true; su_get_element("su_thumbdown_menu_separator").hidden = true; return; } su_get_element("su_thumbdown_menu_separator").hidden = false; var el = su_get_element('su_thumbdown_menu_blockdomain'); el.hidden = false; // for good measure // Handle block domain label var domain = su_get_tld(url); if (domain == null) { el.disabled = true; el.label = "Website: ''"; el.setAttribute("checked", "false"); } else if (domain == su_servername) { el.disabled = true; el.label = "Website: '" + domain + "'"; el.setAttribute("checked", "false"); } else if (su_is_domain_blocked(domain)) { el.disabled = false el.label = "Unblock website: '" + domain + "'"; el.setAttribute("checked", "true"); } else { el.disabled = false el.label = "Block website: '" + domain + "'"; el.setAttribute("checked", "false"); } } function su_show_thumbdown_discovery_alert() { var promptService = su_get_service( "@mozilla.org/embedcomp/prompt-service;1", "nsIPromptService"); promptService.alert( window, "Rating Canceled", "This page is new to StumbleUpon. Use the \n" + "'I like it!' button to add it."); } function su_handle_discovery_dialog_close(event) { var detail = su_ds.lookup("disc_dialog_url:disc_detail", event.URL); if (detail.finalized) return; detail.finalized = true; if (detail.submitted) { su_rate_getmeta(detail.url, true); if (detail.tagtext != "") { var count = su_ds.getValue("$tagged_discovery_count"); count ++; su_ds.setValue("$tagged_discovery_count", count); if (count == 3) { su_ds.setValue("$show_tag", true); su_ds.setValue("$shown_tag", true); su_ds.setValue("$show_flag", true); su_set_visible("su_tag", su_ds.getValue("$show_field")); su_set_visible("su_tag2", (! su_ds.getValue("$show_field"))); // setTimeout( // alert, // 500, // "For convenience, the Tag control has been added to the toolbar.\nIf this is unwelcome, you can remove it via:\ntoolbar->Tools->Toolbar Options."); } var tag = su_normalize_tag(detail.tagtext); su_load_tags(detail.url); // Add the new tag var o = new Object(); o.url = detail.url; o.tag_list = tag; su_tag_lists_by_url[detail.url] = tag; su_tags.unshift(o); su_store_tags(); su_disable_tag_toolbar(tag); su_old_search = tag; } } else { var context = new su_AsyncContext(); context.url = detail.url; context.ref_url = context.url; context.quiet = true; context.discoveryCancelled = true; var params = "url=" + encodeURIComponent(context.url); params = su_append_sync_params(params); su_post_url_server_async( "unrate.php", params, null, su_unrate_done, context); } su_check_progress_listener(); } function su_prepare_reporting_menu(submenu, url_detail, tools_menu, url) { var stumbler_name = su_get_profile_nickname(url); var item; if (! tools_menu) { item = document.createElement("menuitem"); item.setAttribute("label", "This stumble is:"); item.setAttribute("style", "font-weight: bold; color: #404040;"); item.setAttribute("disabled", "true"); submenu.appendChild(item); } if (! stumbler_name) { item = document.createElement("menuitem"); item.setAttribute("label", " Broken or 404"); item.setAttribute("tooltiptext", "Report that this page is broken"); item.setAttribute("oncommand", "su_handle_report_404_command('" + url + "');"); submenu.appendChild(item); } item = document.createElement("menuitem"); item.setAttribute("label", " Factually incorrect"); item.setAttribute("tooltiptext", "Report that this page contains bogus info"); item.setAttribute("oncommand", "su_handle_report_inaccurate_command('" + url + "');"); submenu.appendChild(item); if (tools_menu) { if (stumbler_name) { item = document.createElement("menuitem"); item.setAttribute("label", " Adult content..."); item.setAttribute("tooltiptext", "Report that the " + stumbler_name + " profile contains adult content"); item.setAttribute("oncommand", "su_handle_report_adult_profile_command('" + url + "');"); submenu.appendChild(item); } else { item = document.createElement("menuitem"); if (url_detail) item.setAttribute("label", " Not about " + url_detail.cur_topic_name + "..."); else item.setAttribute("label", " Suggest topic change..."); item.setAttribute("tooltiptext", "Choose a different topic for this page"); item.setAttribute("oncommand", "su_handle_report_miscat_command('" + url + "');"); submenu.appendChild(item); } } if (url_detail && url_detail.language) { item = document.createElement("menuitem"); item.setAttribute("label", " Not in " + url_detail.language + "..."); item.setAttribute("tooltiptext", "Choose a different language for this page"); item.setAttribute("oncommand", "su_handle_report_wrong_language_command('" + url + "');"); submenu.appendChild(item); } item = document.createElement("menuitem"); item.setAttribute("label", " Spam..."); item.setAttribute("tooltiptext", "Report this as bad solicitation"); item.setAttribute("oncommand", "su_handle_report_spam_command('" + url + "');"); submenu.appendChild(item); item = document.createElement("menuitem"); item.setAttribute("label", " Unsafe"); item.setAttribute("tooltiptext", "Report that this page is a security risk"); item.setAttribute("oncommand", "su_handle_report_badware_command('" + url + "');"); submenu.appendChild(item); } function su_prepare_stumble_report_menu(event, url) { if (event.originalTarget.id != "su_stumble_report_popup") return; var submenu = su_get_element("su_stumble_report_popup"); if (submenu.getAttribute("data-url") == url) return; submenu.removeAttribute("data-url"); submenu.setAttribute("data-url", url); // Check if a menu already exists -> If so, we need to remove it var url_detail = su_ds.lookup("url:url_detail", url); while(submenu.childNodes.length) submenu.removeChild(submenu.firstChild); su_prepare_reporting_menu(submenu, url_detail, true, url); } /* // handles discovery dialog accept function su_handle_discovery_dialog_accept(detail) { if (detail.tagtext != "") { var count = su_ds.getValue("$tagged_discovery_count"); count ++; su_ds.setValue("$tagged_discovery_count", count); if (count == 3) { su_ds.setValue("$show_tag", true); su_ds.setValeu("$shown_tag", true); su_ds.setValue("$show_flag", true); su_set_visible("su_tag", su_ds.getValue("$show_field")); su_set_visible("su_tag2", (! su_ds.getValue("$show_field"))); // setTimeout( // alert, // 500, // "For convenience, the Tag control has been added to the toolbar.\nIf this is unwelcome, you can remove it via:\ntoolbar->Tools->Toolbar Options."); } } } // handles discovery dialog cancel function su_handle_discovery_dialog_cancel(detail, state) { var context = new su_AsyncContext(); context.url = detail.rated_uri; context.ref_url = context.url; var params = "url=" + encodeURIComponent(context.url); params = su_append_sync_params(params); su_post_url_server_async( "unrate.php", params, null, su_unrate_done, context); su_check_progress_listener(); } */ // used by ratingDialog to add a comment //function su_add_review(urlid, review) //{ // su_post_url_server_async( // "addcomment.php", // "urlid=" + urlid + // "&comment=" + encodeURIComponent(review), // null, // null, // null); //} function su_handle_error(error) { su_set_server_location('error.php?error=' + error, null, false); } var su_disabled_button_color = null; // // Get the color used by the current theme for disabled buttons because we want to // use that same color for an active thumbup button (but without disabling it) // function su_get_disabled_button_color() { if(!su_disabled_button_color) { try { // Get the current thumbup state var elThumbup = su_get_element("su_thumbup"); var oldMode = elThumbup.getAttribute("mode"); var oldDisabled = elThumbup.disabled; // Disable the button and remove the mode so we can compute the disabled style su_remove_attribute("su_thumbup", "mode"); elThumbup.disabled = true; var disabledStyle = document.defaultView.getComputedStyle(elThumbup, ""); // Restore the thumbup button to its original state if(oldMode) elThumbup.setAttribute("mode", oldMode); elThumbup.disabled = oldDisabled; // And grab the disabled button color from the computed stylesheet if(disabledStyle.color) { su_disabled_button_color = disabledStyle.color; } } catch(ex) { // We are being defensive here because this code is being added late in a release cycle and I'm nervous // about support for getComputedStyle } if(!su_disabled_button_color) { su_disabled_button_color = "GrayText"; } } return su_disabled_button_color; } // Greys out one of the rating buttons function su_disable_toolbar(rating) { // enable everything first so we don't get su_website_info collisions? su_set_image("su_website_info", "chrome://stumbleupon/content/skin/comment.png"); // We use the disabled color for the thumbup button text when the user has already // rated the site var disabledColor = su_get_disabled_button_color(); su_get_element("su_thumbup").style.color = disabledColor; if (rating > 0) { su_set_attribute("su_thumbup", "mode", "thumbup"); su_set_attribute("su_thumbdown", "mode", "thumbup"); su_set_image("su_referral_menu", "chrome://stumbleupon/content/skin/icon_tb_share2.png"); } else { su_set_attribute("su_thumbup", "mode", "thumbdown"); su_set_attribute("su_thumbdown", "mode", "thumbdown"); su_set_image("su_referral_menu", "chrome://stumbleupon/content/skin/icon_tb_share.png"); } su_toolbar_disabled = true; } // Un-greys all the rating buttons function su_enable_toolbar() { su_toolbar_disabled = false; su_remove_attribute("su_thumbup", "mode"); su_get_element("su_thumbup").style.color = ''; su_remove_attribute("su_thumbdown", "mode"); su_get_element("su_thumbup").disabled = false; su_get_element("su_thumbdown").disabled = false; if (!su_get_element("su_website_info").image.indexOf('bubble')) su_get_element("su_website_info").image="chrome://stumbleupon/content/skin/bubble.png"; su_set_image("su_referral_menu", "chrome://stumbleupon/content/skin/icon_tb_share.png"); } // called by the global configure-toolbar event, during init and by // the searchbox context menuitem listeners to set the autocomplete // type for the searchbox function su_set_autocomplete_type(type) { var oldval = su_ds.getValue("$autocomplete_type"); var searchbox = su_get_element('su_searchbox'); if ((type == "auto") && (oldval == "query")) type = "query,tag"; else if ((type == "auto") && (oldval == "tag")) type = "tag,query"; if (type == "query,tag") { searchbox.contextItemAChecked = true; searchbox.contextItemBChecked = false; searchbox.contextItemCChecked = false; su_ds.setValue("$autocomplete_type", "query,tag"); } else if (type == "tag,query") { searchbox.contextItemAChecked = true; searchbox.contextItemBChecked = false; searchbox.contextItemCChecked = false; su_ds.setValue("$autocomplete_type", "tag,query"); } else if (type == "query") { su_ds.setValue("$autocomplete_type", "query"); searchbox.contextItemAChecked = false; searchbox.contextItemBChecked = true; searchbox.contextItemCChecked = false; } else if (type == "tag") { su_ds.setValue("$autocomplete_type", "tag"); searchbox.contextItemAChecked = false; searchbox.contextItemBChecked = false; searchbox.contextItemCChecked = true; } if (oldval != type) searchbox.open = false; } // handles the click event for the searchbox function su_searchbox_click_kludge(eventId) { // This handles value selection in the case where the user is // clicking back and forth between the searchbox and another field // (like urlbar). Without this kludge, the text is selected only // every second time. (ref: Firefox 1.5, XP) -- JW switch (eventId) { case "click": var searchbox = su_get_element('su_searchbox'); var selected = (searchbox.value.length != 0) && ((searchbox.selectionEnd - searchbox.selectionStart) == searchbox.value.length); if ((! su_searchbox_was_focused) && (! selected)) searchbox.select(); su_searchbox_was_focused = true; break; case "blur": su_searchbox_was_focused = false; break; } return true; } // handles the focus event for the searchbox function su_handle_searchbox_focus(event) { var searchbox = su_get_element('su_searchbox'); su_visited_searchbox = 1; if (searchbox.value == su_tag_instructions) { searchbox.value = ''; searchbox.removeAttribute("mode"); } else { if (su_url_has_tag) { su_old_search = searchbox.value; su_enable_tag_toolbar(); } if (! su_keep_searchbox_focus) searchbox.select(); } } // handles the blur event for the searchbox function su_handle_searchbox_blur() { su_searchbox_click_kludge("blur"); } // handles the keyup event for the searchbox function su_handle_searchbox_keyup(evt) { var searchbox = su_get_element('su_searchbox'); if(searchbox.value == su_old_search) return false; su_old_search = searchbox.value; // save the time we last did this var da = new Date(); su_last_typed_tag = da.getTime(); searchbox.removeAttribute("mode"); if (su_old_search == "") su_get_element('su_tag').setAttribute("tooltiptext", su_get_element('su_tag').getAttribute("tooltiptext2")); else su_get_element('su_tag').setAttribute("tooltiptext", "Tag this page as '" + su_get_element('su_searchbox').value + "'"); return true; } // handles the textentered event for the searchbox function su_handle_searchbox_textentered(event) { var autocomplete_type = su_ds.getValue("$autocomplete_type"); if (event.shiftKey) { if (autocomplete_type == "query,tag") su_ds.setValue("$autocomplete_type", "tag,query"); // Shift+Enter tags su_handle_tag_command(false); } else { if (autocomplete_type == "tag,query") su_ds.setValue("$autocomplete_type", "query,tag"); su_old_search = su_get_element('su_searchbox').value; // when you search, we know it's not a tag on i-like-it su_last_typed_tag = 0; var new_tab = false; var platform_ctrl_key = (su_host.mac) ? ((event.keyCode == 77) ? event.ctrlKey : event.metaKey) : event.ctrlKey; if ((event.button == 1) || platform_ctrl_key) new_tab = true; new_tab = new_tab || su_ds.getValue("$search_new_window"); var query = su_get_element("su_searchbox").value; su_stumble_in_tag(su_get_element('su_searchbox').value, new_tab); } } // handles the textreverted event for the searchbox function su_handle_searchbox_textreverted() { if (su_old_search != "") { su_get_element("su_searchbox").value = su_old_search; su_get_element("su_searchbox").select(); su_get_element("su_searchbox").removeAttribute("mode"); } else if (su_url_has_tag) { su_disable_tag_toolbar(su_tag_lists_by_url[su_get_browser_url()]); } } /* function su_handle_searchbox_pagenavigationkey(event) { su_keep_searchbox_focus = false; su_unfocus_searchbox(); setTimeout(function (win, event) { win.su_handle_searchbox_pagenavigationkey_wrapped(event); } , 1000, window, event.keyCode); } function su_handle_searchbox_pagenavigationkey_wrapped(keyCode) { var evt = document.createEvent("KeyboardEvent"); evt.initKeyEvent( "keypress", // in DOMString typeArg, true, // in boolean canBubbleArg, true, // in boolean cancelableArg, null, // in nsIDOMAbstractView viewArg, Specifies UIEvent.view. This value may be null. false, // in boolean ctrlKeyArg, false, // in boolean altKeyArg, false, // in boolean shiftKeyArg, false, // in boolean metaKeyArg, keyCode, // in unsigned long keyCodeArg, 0); // in unsigned long charCodeArg); getBrowser().dispatchEvent(evt); // su_get_element("su_searchbox").focus(); } */ function su_get_autocomplete_results(autocomplete_type, str, max_item_count, supplemental_candidates) { var types = autocomplete_type.split(","); var i; var items = new Array(); for (i = 0; i < types.length; i++) items = su_get_autocomplete_results2(types[i], str, max_item_count, items, supplemental_candidates); return items; } // ultimately called by the searchbox to get an array of items to // populate the autocomplete list function su_get_autocomplete_results2(autocomplete_type, str, max_item_count, items, supplemental_candidates) { // Each array item is an object with properties that are analogous // to attributes of the autocomplete list item. In other words, // item.label results in the search widget doing something like: // autocomplete-item.setAttribute("label", item.label); // -- JW // Supplemental candidate matches are placed at the top of the // results. Other items are ranked in the autocomplete list in the // same order as they appear in the queries and tags files, which // is to say in reverse chronological order. But we may want to // add a heuristic that places more frequently used tags & queries // near the top. -- JW var pre_items_count = items.length; var source; var o; if ((str == "") || (str == su_tag_instructions)) { // add recent items if (autocomplete_type == "query") { su_load_queries(); source = su_queries; } else if (autocomplete_type == "tag") { su_load_tags(null); source = su_tags; } for (var i = (- supplemental_candidates.length); (i < source.length) && (items.length <= max_item_count); i++) { var candidate; if (i < 0) { candidate = supplemental_candidates[-i - 1]; } else { if (source == su_queries) candidate = source[i]; else if (source == su_tags) candidate = source[i].tag_list; } if (candidate.search(/^\s*$/) != -1) continue; var duplicate = false; for (var j = 0; j < items.length; j++) { if (candidate == items[j].label) { duplicate = true; if (j < pre_items_count) items[j].style = "color:#ff3300;"; break; } } if (! duplicate) { o = new Object(); o.label = candidate; if (autocomplete_type == "tag") o.style = "color:#ff3300;"; items.push(o); } } } else { // add the subset of items if (autocomplete_type == "query") { if (str.length == 1) su_load_queries(); source = su_queries; } else if (autocomplete_type == "tag") { if (str.length == 1) su_load_tags(null); source = su_tags; } str = su_normalize_tag(str); str = su_escape_regexp_chars(str); var pattern = new RegExp("^" + str + "|, " + str, "i"); for (var i = (- supplemental_candidates.length); (i < source.length) && (items.length <= max_item_count); i++) { var candidate if (i < 0) { candidate = supplemental_candidates[-i - 1]; } else { if (source == su_queries) candidate = source[i]; else if (source == su_tags) candidate = source[i].tag_list; } if (candidate.search(/^\s*$/) != -1) continue; if (candidate.search(pattern) != -1) { var duplicate = false; for (var j = 0; j < items.length; j++) { if (candidate == items[j].label) { duplicate = true; if (j < pre_items_count) items[j].style = "color:#ff3300;"; break; } } if (! duplicate) { o = new Object(); o.label = candidate; if (autocomplete_type == "tag") o.style = "color:#ff3300;"; items.push(o); } } } } // o = new Object(); // o.style = "-moz-binding: url(chrome://global/content/bindings/menu.xml#menuitem-iconic);"; // o.image = "chrome://stumbleupon/content/skin/icon_tb_photo_hover.png"; // o.label = "Photos"; // items.push(o); return items; } // adds tag to toolbar function su_disable_tag_toolbar(tag) { if (!su_url_has_tag) su_old_search = su_get_element("su_searchbox").value; su_url_has_tag = true; su_get_element("su_searchbox").value = tag; // This timeout kludge fixes a bug where DOM change events aren't being // generated when setAttribute is called within the execution path of a // textreverted event handler for the su_searchbox. (ref: Firefox 1.5, // XP) -- JW setTimeout('su_get_element("su_searchbox").setAttribute("mode", "tag")', 0); su_get_element("su_tag").image="chrome://stumbleupon/content/skin/tag2.png"; su_get_element('su_tag').setAttribute("tooltiptext", "Page tagged as '" + tag + "'. Click to remove."); su_get_element("su_tag2").image="chrome://stumbleupon/content/skin/tag2.png"; su_get_element('su_tag2').setAttribute("tooltiptext", "Page tagged as '" + tag + "'. Click to remove."); } // removes tag from toolbar function su_enable_tag_toolbar() { su_url_has_tag = false; if (su_visited_searchbox == 0) { su_get_element("su_searchbox").value = su_tag_instructions; su_get_element("su_searchbox").setAttribute("mode", "prompt"); } else if (su_old_search != "") { su_get_element("su_searchbox").value = su_old_search; su_get_element("su_searchbox").removeAttribute("mode"); } else { su_get_element("su_searchbox").removeAttribute("mode"); } su_get_element("su_tag").image="chrome://stumbleupon/content/skin/tag.png"; su_get_element("su_tag2").image="chrome://stumbleupon/content/skin/tag.png"; if (su_old_search == "") { su_get_element('su_tag').setAttribute("tooltiptext", su_get_element('su_tag').getAttribute("tooltiptext2")); su_get_element('su_tag2').setAttribute("tooltiptext", su_get_element('su_tag2').getAttribute("tooltiptext2")); } else { su_get_element('su_tag').setAttribute("tooltiptext", "Tag this page as '" + su_old_search + "'"); su_get_element('su_tag2').setAttribute("tooltiptext", "Tag this page as '" + su_old_search + "'"); } return true; } // su_sign_up_page is the web site's sign up page function su_sign_up_page(url) { su_visited_login_page = true; su_verify_cookie_perms(false); su_ds.setValue("~visited_signup", true); if (su_is_server_page(url, "sign_up.php?pre2=login")) su_login_behavior_page(); } function su_login_behavior_page() { su_visited_login_page = true; setTimeout(su_show_signin_dialog, 0); } function su_attach_api(doc) { try { var win = doc.defaultView.wrappedJSObject; win.suToolbarApi = su_toolbar_api; if(win.onSuToolbarApiReady) { win.onSuToolbarApiReady(); } } catch(ex) { // Older browsers might not support wrappedJSObject, be defensive here. } } function su_wire_portal_links(doc) { var el; var links; var i; //!!! This could be pretty expensive on pages with large link count. // Unfortunately, we link to login.php many places besides the // header (i.e. a send message error on the public view of // a Favorites page). // el = doc.getElementById("headerLoginLink"); // if (el) // el.addEventListener("click", su_handle_page_login_click, true); el = doc.getElementById("downloadFavoritesLink"); if (el) el.addEventListener("click", su_handle_page_favorites_download_click, true); el = doc.getElementById("stumble_search"); if (el) el.addEventListener("click", su_handle_page_search_click, true); } function su_handle_page_login_click(event) { setTimeout(su_show_signin_dialog, 0); return su_cancel_event(event); } function su_handle_page_logout_click(event) { if (stumbleid == 0) return true; setTimeout("su_handle_logout(true)", 0); return su_cancel_event(event); } function su_handle_page_favorites_download_click(event) { var ps; if (! su_host.places) { ps = su_get_service( "@mozilla.org/embedcomp/prompt-service;1", "nsIPromptService"); ps.alert(window, "StumbleUpon", "You must have Firefox 3 or greater to download favorites."); return; } if (stumbleid == 0) { ps = su_get_service( "@mozilla.org/embedcomp/prompt-service;1", "nsIPromptService"); ps.confirm(window, "StumbleUpon", "You must be signed-in to download favorites."); return; } setTimeout(su_handle_download_favs_command, 0); return su_cancel_event(event); } function su_handle_page_search_click(event) { var el; var doc = event.target.ownerDocument; el = doc.getElementById("search_q"); if (el.value != "") su_stumble_in_tag(el.value, su_new_tab(event)); return su_cancel_event(event); } // su_signup_page is the sign up page that the toolbars sends them to. function su_signup_page(doc) { su_verify_cookie_perms(false); var el; el = doc.getElementById("interests"); if (el) su_set_legacy_user_interests(el.innerHTML); var init_toolbar = (doc.getElementById("signup_success") != null); el = doc.getElementById("challenge"); if (el && el.hasAttribute("value") && (el.getAttribute("value") != "")) { su_init_new_user(el.getAttribute("value"), init_toolbar); } else if (init_toolbar) { su_new_user = false; var detail = new Object(); detail.skip_cookies = false; detail.ignore_cookies = true; detail.new_profile = true; detail.new_user_prompt = true; su_invoke_global_event("login", detail); } else if (stumbleid != 0) { su_store_user_interests(); su_refresh_category_selector_batched(); } } function su_login_page_after() { var userid_saved = stumbleid; var profile_change = su_process_cookies(false); if (profile_change && (stumbleid != userid_saved)) { var detail = new Object(); detail.skip_cookies = true; detail.ignore_cookies = true; detail.new_profile = profile_change.new_profile; detail.new_user_prompt = false; su_invoke_global_event("login", detail); } } function su_find_friends_page(url) { su_ds.setValue("~visited_find_friends", true); var userid_saved = stumbleid; var profile_change = su_process_cookies(false); if (profile_change && (stumbleid != userid_saved)) { var detail = new Object(); detail.skip_cookies = true; detail.ignore_cookies = true; detail.new_profile = true; detail.new_user_prompt = true; su_invoke_global_event("login", detail); } else { if (su_ds.getValue("#find_friends_optin")) { su_ds.incrementValue("$shown_find_friends_clicks"); if ((! su_ds.getValue("$show_searchlinks_score")) && (! su_ds.getValue("$show_searchlinks_friends"))) { su_ds.setValue("$show_searchlinks_score", true); su_ds.setValue("$show_searchlinks_friends", true); } else { su_ds.setValue("$show_searchlinks_friends", true); } su_ds.setValue("#find_friends_optin", false); } } if (stumbleid) su_ds.setValue("$shown_find_friends", true); su_ds.flushPrefs(); } function su_find_friends_after_page() { su_ds.setValue("$shown_find_friends", true); var now_s = su_get_time_s(); var pre = su_ds.getValue("#find_friends_pre"); if (pre == "facebook") su_ds.setValue("$imported_fbcontacts_time_s", now_s); else su_ds.setValue("$imported_contacts_time_s", now_s); su_ds.setValue("#find_friends_pre", ""); su_ds.flushPrefs(); setTimeout("su_import_contacts();", 15000); } function su_stumblevideo_page(doc, from_load) { var el = doc.getElementById("url_command"); if (! el) return; su_handle_stumblevideo_change(null, doc); el.removeEventListener("DOMAttrModified", su_handle_stumblevideo_change, false); el.addEventListener("DOMAttrModified", su_handle_stumblevideo_change, false); var el2 = doc.getElementById("login_count"); if (el2) { el2.removeEventListener("DOMAttrModified", su_handle_stumblevideo_login, false); el2.addEventListener("DOMAttrModified", su_handle_stumblevideo_login, false); } el = doc.getElementById("thumbUp"); if (el) { el.removeEventListener("DOMAttrModified", su_handle_stumblevideo_rate, false); el.addEventListener("DOMAttrModified", su_handle_stumblevideo_rate, false) } el = doc.getElementById("thumbDown"); if (el) { el.removeEventListener("DOMAttrModified", su_handle_stumblevideo_rate, false); el.addEventListener("DOMAttrModified", su_handle_stumblevideo_rate, false) } // if (su_pending_stumblevideo_stumble) // su_dispatch_click(doc, "stumbleButton"); // // su_pending_stumblevideo_stumble = false; } function su_handle_stumblevideo_login(event) { if (event.target.id != "login_count") return true; var userid_saved = stumbleid; var profile_change = su_process_cookies(false); if (profile_change && (stumbleid != userid_saved)) { var detail = new Object(); detail.skip_cookies = true; detail.ignore_cookies = true; detail.new_profile = profile_change.new_profile; detail.new_user_prompt = false; su_invoke_global_event("login", detail); } return true; } function su_get_browser_from_doc(doc) { var browsers = getBrowser().browsers; var i; var browser = null; for (i = 0; i < browsers.length; i++) { if (browsers[i].contentDocument == doc) { browser = browsers[i]; break; } } if (! browser) su_log("MISSING BROWSER"); return browser; } function su_handle_stumblevideo_change(opt_event, opt_doc) { su_stumble_async_context = null; su_get_element("su_stumble").image="chrome://stumbleupon/content/skin/stumble.png"; var command; var doc; if (opt_event) { if (opt_event.target.id != "url_command") return true; command = opt_event.newValue; doc = opt_event.target.ownerDocument; } else if (opt_doc) { doc = opt_doc; var el = doc.getElementById("url_command"); if (! el) return true; if (! el.hasAttribute("value")) return true; command = el.getAttribute("value"); } if (command.indexOf("URL ") != 0) return true; var target_browser = su_get_browser_from_doc(doc); if (! target_browser) return true; var overlay_url_detail = su_deserialize_url_command_params(command.substr(4), false); var display_url = su_get_browser_url(doc, true); var url_detail = su_ds.lookup("url:url_detail", display_url); if (url_detail) { url_detail.url = overlay_url_detail.url; url_detail.display_url = display_url; } else { url_detail = overlay_url_detail; url_detail.display_url = display_url; } if (target_browser.su_url_detail && (url_detail != target_browser.su_url_detail) && target_browser.su_url_detail.messageid) su_close_message(target_browser.su_url_detail.messageid, true); target_browser.su_url_detail = url_detail; // su_dd("setstumbled", 2, url_detail.url); stumbled_url = url_detail.url; su_redirect_url = url_detail.url; stumbled_redirect = ""; // su_dd("reset", 3); su_refresh_pagemeta(true, 4); return true; } function su_get_stumblevideo_detail(opt_doc) { var browser = null; if (opt_doc) { browser = su_get_browser_from_doc(opt_doc); if (! browser) return null; } else { browser = getBrowser().selectedBrowser; } if (! browser.su_url_detail) return null; var cmp_url = browser.currentURI.asciiSpec; // su_log("svdetail.1"); if (! ((cmp_url.indexOf("http://video." + su_servername + "/#p") == 0) || (cmp_url.indexOf("http://video." + su_servername + "/?p") == 0))) return null; // su_log("svdetail.2"); return browser.su_url_detail; } function su_handle_stumblevideo_rate(opt_event, opt_doc) { // Determine the rating var rating = null; var unrate = false; var other_button; var doc; if (opt_event) { var event = opt_event; if (event.attrName != "src") return true; doc = event.target.ownerDocument; if (event.target.id == "thumbUp") { other_button = doc.getElementById("thumbDown"); if (event.newValue.indexOf("_sel") != -1) rating = 1; else if ((event.prevValue.indexOf("_sel") != -1) && (event.newValue.indexOf("_sel") == -1) && (other_button.src.indexOf("_sel") == -1)) unrate = true; } else if (event.target.id == "thumbDown") { other_button = doc.getElementById("thumbUp"); if (event.newValue.indexOf("_sel") != -1) rating = 0; else if ((event.prevValue.indexOf("_sel") != -1) && (event.newValue.indexOf("_sel") == -1) && (other_button.src.indexOf("_sel") == -1)) unrate = true; } } else if (opt_doc) { var doc = opt_doc; var thumbup = doc.getElementById("thumbUp"); var thumbdown = doc.getEementById("thumbDown"); if (thumbup && thumbup.src && (thumbup.src.indexOf("_sel") != -1)) rating = 1; else if (thumbdown && thumbdown.src && (thumbdown.src.indexOf("_sel") != -1)) rating = 0; else if (thumbup && thumbdown && thumbup.src && thumbdown.src && (thumbup.src.indexOf("_sel") == -1) && (thumbdown.src.indexOf("_sel") == -1)) unrate = true; } if (! (unrate || (rating != null))) return true; // Record the rating var url_detail = su_get_stumblevideo_detail(doc); // su_log(1); if (! url_detail) { return true; } // su_log(2); var context = new su_AsyncContext(); context.rating = rating; context.url = url_detail.url; if (rating != null) { if (doc == getBrowser().contentDocument) context.browser = getBrowser().selectedBrowser; else contect.browser = null; context.title = null; context.force_nostumble = true; context.force_comment = null; context.timestamp = null; context.open_reviews = null; context.charset = null; context.referrer = null; context.stumblevideo_mode = (su_stumblevideo_toolbar_rate) ? "toolbar" : "page"; } var res = new Object(); res.detail = context; res.status = 200; res.responseText = ""; if (context.rating == null) { url_detail.rating = -1; setTimeout(su_unrate_done, 0, res); setTimeout(su_rate_getmeta, 0, context.url, true); } else { url_detail.rating = rating; setTimeout(su_rate_done, 0, res); setTimeout(su_rate_getmeta, 0, context.url, true); } return true; } function su_rate_getmeta(url, new_rating) { if (! su_host.places) return; var params = ""; params = su_arp(params, "url", url); params = su_append_sync_params(params); var context = new su_AsyncContext(); context.url = url; context.ref_url = url; context.quiet = true; var loc = (new_rating) ? "getmetanew.php" : "getmetahist.php"; su_post_url_server_async( loc, params, null, su_rate_getmeta_done, context); } function su_rate_getmeta_done(res) { var context = res.detail; try { if (res.status != 200) return; } catch (e) { return; } var s = ""; if (typeof(res.responseText) != "undefined") s = res.responseText; if (su_log_communication) su_log("response " + context.request_target, s); su_process_commands(s, context); su_refresh_pagemeta(false, 8); } function su_facebook_page(doc, url) { if (url.match(/^http.*?\/\/[^\/]*?\.facebook\.com\/home\.php/)) su_facebookhome_page(doc); else if (url.match(/^http.*?\/\/[^\/]*?\.facebook\.com\/friends\.php\?r/)) su_facebookfriends_page(doc); if (su_ds.getValue("@facebook_user") && (su_ds.getValue("@id_list") == "") && (! su_ds.getValue("~shown_prompt2")) && su_ds.getValue("@enable_prompt2") && (! su_ds.getValue("~visited_find_friends"))) { su_ds.setValue("~shown_prompt2", true); var detail = new Object(); detail.post_url = url; su_show_banner( "Join StumbleUpon to share you discoveries with your friends on Facebook", "chrome://stumbleupon/content/skin/stumble.png", function () { su_handle_prompt_click("prompt2", "accept", detail); }, function () { su_handle_prompt_click("prompt2", "decline", detail); }); // var detail = new Object(); // detail.target = "prompt2"; // detail.post_url = doc.location.toString(); // su_show_notifier( // "Create a StumbleUpon account to see ratings, reviews and recommendations by Facebook friends.", // "chrome://stumbleupon/content/skin/logo32.png", // "notifierIcon32", // 5000, // detail); } var fbuserid = su_get_facebook_userid(); if (fbuserid) { su_ds.setValue("#facebook_userid", fbuserid); su_ds.setValue("#checked_facebook", false); su_ds.setValue("@facebook_user", true); } } function su_facebookhome_page(doc) { if (stumbleid == 0) return; var now_s; var shown_time_s; if (! su_test_facebookhome_prompt) { if (su_ds.getValue("$facebook_added")) return; if (su_ds.getValue("$facebook_homeprompt_optout")) return; if (! su_ds.getValue("@toolbar-visible")) return; now_s = su_get_time_s(); shown_time_s = su_ds.getValue("$facebook_homeprompt_time_s"); if (shown_time_s && ((now_s - shown_time_s) > (2 * 7 * 24 * 60 * 60))) return; if (! su_ds.getValue("#checked_facebook")) { su_get_facebook(doc); return; } if (! su_get_facebook_userid()) return; } var target = null; var el = doc.getElementById("home_main"); if (! el) return; var hs = el.getElementsByTagName("h2"); var i; for (i = 0; i < hs.length; i++) { if (hs[i].innerHTML.indexOf("News Feed") != -1) { target = hs[i]; break; } } if (! target) return; if (! target.parentNode) return; var sibling = target.nextSibling; if (sibling != target.parentNode.lastChild) return; // var sibling = sibling.firstChild; if (! sibling) return; var tooltip = "Share websites with friends"; var str = ""; str += ' '; str += '<a style="text-decoration:none;" title="' + tooltip + '" href="http://apps.facebook.com/stumbleupon/"><img border="0" width="13" height="13" style="display:inline;position:relative;top:2px;" src="chrome://stumbleupon/content/skin/smallstumble.png"/> </a><a title="' + tooltip + '" href="http://apps.facebook.com/stumbleupon/">Add StumbleUpon</a> <img border="0" width="13" height="12" style="display:inline;cursor:pointer;" src="chrome://stumbleupon/content/skin/close-c.png"/>'; // str += " <span style="text-size:small;">·</span> "; el = doc.createElement("span"); el.innerHTML = str; el.setAttribute("style", "float:left;"); sibling.parentNode.insertBefore(el, sibling); el.lastChild.addEventListener("click", su_handle_facebook_homeprompt_optout_click, false); if (! su_test_facebookhome_prompt) { if (! shown_time_s) su_ds.setValue("$facebook_homeprompt_time_s", now_s); } } function su_handle_searchpageprompt_optout_click(event) { su_handle_prompt_optout_click(event, "search"); } function su_handle_facebook_homeprompt_optout_click(event) { su_handle_prompt_optout_click(event, "fbhome"); } function su_handle_prompt_optout_click(event, promptid) { var ps = su_get_service( "@mozilla.org/embedcomp/prompt-service;1", "nsIPromptService"); var out = ps.confirmEx( window, "StumbleUpon Confirm", "Do you want to permanently remove this StumbleUpon link?", ps.STD_YES_NO_BUTTONS, null, null, null, null, {}); if (out == 0) { switch (promptid) { case "fbhome": var target = event.target.parentNode; target.parentNode.removeChild(target); su_ds.setValue("$facebook_homeprompt_optout", true); break; case "search": var target = event.target.parentNode; target.parentNode.removeChild(target); su_ds.setValue("$shown_find_friends_optout", true); break; } } } function su_facebookfriends_page(doc) { if (! su_ds.getValue("@toolbar-visible")) return; var el = doc.getElementById("friendtables"); if (! el) return; var as = el.getElementsByTagName("a"); var targets = new Array(); var userids = new Array(); for (i = 0; i < as.length; i++) { var match = as.item(i).href.match(/http\:\/\/[^\/]*\.facebook\.com\/addfriend\.php\?id=(.*)/); if (! match) match = as.item(i).href.match(/http\:\/\/[^\/]*\.facebook\.com\/friends\.php\?remove_friend=1\&friend_id=(.*)/); if (! match) continue; var target = as.item(i).parentNode; if (! target) continue; if (target.className != "actions") continue; userids.push(match[1]); targets.push(target); } if (userids.length == 0) return; // su_check_facebook_contacts(userids, targets); } /* function su_check_facebook_contacts(fb_userids, targets) { var i; var contact; var contacts = su_ds.selectAllRows("contact"); var contacts_by_fbid = new Object(); var now_s = su_get_time_s(); var checked_time_s = su_ds.getValue("$facebook_contacts_time_s"); var refresh_cache = (checked_time_s && ((now_s - checked_time_s) > (18 * 60 * 60))); var anonymize_nonmutuals = refresh_cache; for (i = 0; i < contacts.length; i++) { contact = contacts[i]; if (contact.fbid) { contacts_by_fbid[contact.fbid] = contact; if (anonymize_nonmutuals && contact.contactid && (! contact.mutual)) { contact.contactid = ""; contact.nickname = ""; su_ds.updateRow(contact); } } } for (i = 0; i < fb_userids.length; i++) { if (contacts_by_fbid[fb_userids[i]]) contact var contactid = friends[i].split(".")[0]; var nickname = friends[i].split(".")[1]; var facebookid = friends[i].split(".")[2]; fbfriends[contactid] = true; contact = null; if (contacts_by_id[contactid]) contact = contacts_by_id[contactid]; if (contact) { contact.nickname = nickname; contact.fbid = facebookid; su_ds.updateRow(contact); } else { contact = new Object(); contact.contactid = contactid; contact.nickname = nickname; contact.fbid = facebookid; su_ds.insertRow("contact", contact); contacts_by_id[contactid] = contact; } } for (i = 0; i < contacts.length; i++) { if ((typeof (contacts[i].contactid)) != "undefined") { if (contacts[i].fbid && (! fbfriends[contacts[i].contactid])) contacts[i].fbid = 0; su_ds.updateRow(contacts[i]); } } if (userids) { } } */ function su_search_results_page(doc, service_id) { su_search_service_page(doc, service_id); su_augment_links(doc, service_id); } function su_search_service_page(doc, service_id) { var now_s; var shown_time_s; if (! su_test_searchpage_prompt) { if (! su_ds.hasFeature("$sociallinks")) return; if (! su_ds.getValue("@toolbar-visible")) return; if (su_ds.getValue("$imported_contacts_time_s")) return; if (su_ds.getValue("$shown_find_friends_optout")) return; // if ((! su_ds.hasFeature("$unlimitedslpromptclicks") && // (su_ds.getValue("$shown_find_friends_clicks") >= 3))) // return; now_s = su_get_time_s(); shown_time_s = su_ds.getValue("$shown_find_friends_time_s"); if (shown_time_s && ((now_s - shown_time_s) > (3 * 7 * 24 * 60 * 60))) return; } var tooltip = "Add StumbleUpon friends to see which search results they prefer"; var str = '<a style="text-decoration:none;" title="' + tooltip + '" href="' + su_serverhttp + 'find_friends.php?pre3=' + service_id + '">'; if (su_ds.getValue("$show_searchlinks_logo")) str += '<img border="0" width="13" height="13" style="display:inline;position:relative;top:1px;" src="http://cdn.stumble-upon.com/images/embed/smallstumble.png"> <u style="position:relative;top:-1px;">See friend reviews</u></a> <img border="0" width="13" height="12" style="display:inline;cursor:pointer;" src="chrome://stumbleupon/content/skin/close-c.png"/>'; else str += '<u>See StumbleUpon friend reviews</u></a> <img border="0" width="13" height="12" style="display:inline;cursor:pointer;" src="chrome://stumbleupon/content/skin/close-c.png"/>'; switch (service_id) { // case "google": // str = " " + str; // var target = null; // var el = doc.getElementById("gbar"); // if (! el) // return; // var us = el.getElementsByTagName("u"); // var i; // for (i = 0; i < us.length; i++) // { // if (us[i].innerHTML == "more") // { // target = us[i]; // break; // } // } // if (! target) // return; // // target = target.parentNode; // // if (! target) // return; // // target = target.parentNode; // // if (! target) // return; // // target = target.nextSibling; // // if (! target) // return; // // if (! target.parentNode) // return; // // el = doc.createElement("span"); // el.innerHTML = str; // // target.parentNode.insertBefore(el, target); // el.lastChild.addEventListener("click", su_handle_searchpageprompt_optout_click, false); // break; case "google": case "google-ajax": case "googlenews": // Add listeners for results that are populated by Ajax. if(service_id == "google-ajax") { // Google classic uses ajax to populate the search results, so we need to do // our augmentation work when the results are all inserted, which is whenever the xfoot // element is inserted. if(!doc.__su__listening_ff) { doc.__su__listening_ff = true; doc.addEventListener("DOMNodeInserted", function(event) { if(event.target.id == "xfoot") { if(!doc.getElementById("__su__service_ff")) { su_search_service_page(doc, service_id); } } }, false); } } var el = doc.getElementById("gbar"); if (! el) return; var us = el.getElementsByTagName("u"); var target = null; var i; for (i = 0; i < us.length; i++) { if (us[i].innerHTML == "more") { target = us[i]; break; } } if (! target) return; target = target.parentNode; if (! target) return; // target = target.parentNode; // if (! target) // return; if (! target.parentNode) return; el = doc.createElement("td"); el.id = "__su__service_ff"; el.setAttribute("nowrap", "nowrap"); el.innerHTML = str; target.parentNode.appendChild(el); el.lastChild.addEventListener("click", su_handle_searchpageprompt_optout_click, false); break; case "googleindex": case "googlevideo": var el = doc.getElementById("gbar"); if (! el) return; var us = el.getElementsByTagName("u"); var target = null; var i; for (i = 0; i < us.length; i++) { if (us[i].innerHTML == "more") { target = us[i]; break; } } if (! target) return; target = target.parentNode; if (! target) return; target = target.parentNode; if (! target) return; if (! target.parentNode) return; el = doc.createElement("td"); el.setAttribute("nowrap", "nowrap"); el.innerHTML = str; target.parentNode.appendChild(el); el.lastChild.addEventListener("click", su_handle_searchpageprompt_optout_click, false); break; case "yahoo": str = ' <a style="text-decoration:none;" title="' + tooltip + '" href="' + su_serverhttp + 'find_friends.php?pre3=' + service_id + '">'; if (su_ds.getValue("$show_searchlinks_logo")) str += '<img border="0" width="13" height="13" style="display:inline;position:relative;top:2px;" src="http://cdn.stumble-upon.com/images/embed/smallstumble.png"> <u style="color:rgb(21,73,193);">See friend reviews</u></a> <img border="0" width="13" height="12" style="display:inline;cursor:pointer;" src="chrome://stumbleupon/content/skin/close-c.png"/>'; else str += '<u style="color:rgb(21,73,193);">See StumbleUpon friend reviews</u></a> <img border="0" width="13" height="12" style="display:inline;cursor:pointer;" src="chrome://stumbleupon/content/skin/close-c.png"/>'; var target = doc.getElementById("tabs"); var style = "white-space:nowrap;position:relative;top:-1px;" if (! target) { target = doc.getElementById("eb"); style = "white-space:nowrap;position:relative;top:-2px;"; } if (! target) return; target.setAttribute("style", "white-space:nowrap;"); var el = doc.createElement("span"); el.setAttribute("style", style); el.innerHTML = str; target.appendChild(el); el.lastChild.addEventListener("click", su_handle_searchpageprompt_optout_click, false); break; case "ask": str = ' <a style="text-decoration:none;" title="' + tooltip + '" href="' + su_serverhttp + 'find_friends.php?pre3=' + service_id + '">'; if (su_ds.getValue("$show_searchlinks_logo")) str += '<img border="0" width="13" height="13" style="display:inline;position:relative;top:1px;" src="http://cdn.stumble-upon.com/images/embed/smallstumble.png"> <span style="color:blue;">See friend reviews</span></a> <img border="0" width="13" height="12" style="display:inline;cursor:pointer;" src="chrome://stumbleupon/content/skin/close-d.png"/>'; else str += '<span style="color:blue;">See StumbleUpon friend reviews</span></a> <img border="0" width="13" height="12" style="display:inline;cursor:pointer;" src="chrome://stumbleupon/content/skin/close-d.png"/>'; var target = doc.getElementById("navbar_tabs"); if (! target) return; var el = doc.createElement("span"); el.innerHTML = str; target.appendChild(el); el.lastChild.addEventListener("click", su_handle_searchpageprompt_optout_click, false); break; case "aol": var target = doc.getElementById("morecsb"); if (! target) return; target = target.parentNode; if (! target) return; target = target.parentNode; if (! target) return; var el = doc.createElement("span"); el.innerHTML = str; target.appendChild(el); el.lastChild.addEventListener("click", su_handle_searchpageprompt_optout_click, false); break; } if (! su_test_searchpage_prompt) { if (! shown_time_s) su_ds.setValue("$shown_find_friends_time_s", now_s); } } // extracts links from a page and calls links.php function su_augment_links(doc, service_id) { if ((! su_ds.getValue("$show_searchlinks_score")) && (! su_ds.getValue("$show_searchlinks_friends")) && (! su_ds.getValue("$show_searchlinks_topic"))) return; if (! su_ds.getValue("@toolbar-visible")) return; var as; var target; var el; switch (service_id) { case "wikipedia": el = doc.getElementById("top"); while (el) { if (el.className == "firstHeading") break; el = el.nextSibling; } if (! el) return; var title = el; var title_text = title.innerHTML; title.innerHTML = ""; var inline = doc.createElement("span"); title.appendChild(inline); target = doc.createElement("span"); target.innerHTML = title_text; inline.appendChild(target); break; case "cnn": var el = doc.getElementById("cnnSearchResults"); if (! el) return; as = el.getElementsByTagName("a"); break; default: as = doc.getElementsByTagName("a"); break; } var urls = new Array(); var targets = new Array(); var hrefs = urls; var i; var linked_color = "rgb(130, 132, 204)"; var unlinked_color = "rgb(0, 0, 0)"; var underline = true; var font_size = "100%"; var force_no_logo = false; var force_inline = false; var soft_wrap = false; var hard_wrap = false; var force_logo = false; var before_targets = targets; var after_targets = targets; var include_topic = false; var image_baseline = false; var enable_click_tracking = true; // Check whether we need to add listeners for results that are populated by Ajax. if( (service_id == "google-ajax") || (service_id == "googlevideo") ) { // Google classic uses ajax to populate the search results, so we need to do // our augmentation work when the results are all inserted, which is whenever the xfoot // element is inserted. var idlast = ""; if(service_id == "google-ajax") { idlast = "xfoot"; } else if(service_id == "googlevideo") { idlast = "pagi"; } if(!doc.__su__listening) { doc.__su__listening = true; doc.addEventListener("DOMNodeInserted", function(event) { if(event.target.id == idlast) { su_augment_links(doc, service_id); } }, false); } } switch (service_id) { case "google-ajax": case "google": after_targets = new Array(); linked_color = "#7777cc"; unlinked_color = linked_color; font_size = "smaller"; for (i = 0; i < as.length; i++) { if (as.item(i).className == "l") { if (as.item(i).firstChild && (as.item(i).firstChild.tagName == "IMG") && (as.item(i).firstChild.src.indexOf("/mapfiles/") != -1)) continue; // at top var redir_match = as.item(i).href.match(/^http.*?\/\/[^\/]*?(google\.[^\.]+|google\.co\.[^\.]+)\/(url.*[?&]q=)([^&]+)/); if (redir_match && redir_match.length >= 4) urls.push(decodeURIComponent(redir_match[3])); else urls.push(as.item(i).href); targets.push(as.item(i)); if (as.item(i).parentNode.nextSibling && as.item(i).parentNode.nextSibling.tagName == "FONT" && as.item(i).parentNode.nextSibling.firstChild && as.item(i).parentNode.className != "r") after_targets.push(as.item(i).parentNode.nextSibling.firstChild); else after_targets.push(as.item(i)); } } break; case "googlenews": case "googlenewsindex": after_targets = new Array(); enable_click_tracking = su_ds.hasFeature("$newsclicktracking"); linked_color = "#7777cc"; unlinked_color = linked_color; font_size = "smaller"; for (i = 0; i < as.length; i++) { if (as.item(i).parentNode.className == "title") { if (as.item(i).href.indexOf("http://news.google.co") == 0) continue; urls.push(as.item(i).href); targets.push(as.item(i)); after_targets.push(as.item(i)); } } break; case "googlevideo": linked_color = "#7777cc"; font_size = "small"; force_logo = su_ds.getValue("$show_searchlinks_logo"); hrefs = new Array(); for (i = 0; i < as.length; i++) { var anchor = as.item(i); if (anchor.parentNode.className == "rl-title") { urls.push(anchor.href); targets.push(anchor); } } break; case "ask": linked_color = "auto"; for (i = 0; i < as.length; i++) { if (as.item(i).className == "L4") { var matches = as.item(i).href.match(/&u=([^&]*)/); if(matches && matches[1]) { urls.push(decodeURIComponent(matches[1])); } else { urls.push(as.item(i).href); } targets.push(as.item(i)); } } break; case "bing": var h3s = doc.getElementsByTagName("h3"); for (var i = 0; i < h3s.length; i++) { var anchors = h3s[i].getElementsByTagName("a"); if (anchors.length == 1) { var a = anchors[0]; urls.push(a.href); targets.push(a); } } break; case "bing-news": var headlines = doc.getElementsByClassName("Headline"); for (var i = 0; i < headlines.length; i++) { var anchors = headlines[i].getElementsByTagName("a"); if (anchors.length == 1) { var a = anchors[0]; urls.push(a.href); targets.push(a); } } break; case "nyt": force_inline = true; var h3s = doc.getElementsByTagName("h3"); for (var i = 0; i < h3s.length; i++) { var anchors = h3s[i].getElementsByTagName("a"); if (anchors.length == 1) { var href = anchors[0].href; // They include search referral and search term information at the end of the URL, // past the ?scp=, so we strip that out if it exists. var match = href.match(/(.*?)(\?scp=.*)/); if(match) { href = match[1]; } urls.push(href); targets.push(anchors[0]); } } break; case "yahoo": // Yahoo changes the href with global script, so we have to wait for // the "load" event at which point the href will have been set to the final URL. if(!doc.__su__listening) { doc.__su__listening = true; doc.defaultView.addEventListener("load", function(event) { if(event.target.__su__listening) { su_augment_links(doc, service_id); } }, false); return; } // We got back in here from the load event, now do our work. soft_wrap = true; hrefs = new Array(); for (i = 0; i < as.length; i++) { if ((as.item(i).className.indexOf("yschttl") != -1) )// && as.item(i).href.match(/\*\*(.*)/)) { var href = as.item(i).href; var match = href.match(/http\:\/\/rds.yahoo.com.*?\*\*(.*)/); if(match && match[1]) { href = decodeURIComponent(match[1]); } urls.push(href); hrefs.push(href); targets.push(as.item(i)); } } break; case "aol": font_size = "larger"; hrefs = new Array(); for (i = 0; i < as.length; i++) { if (as.item(i).className == "find") { hrefs.push(as.item(i).href); urls.push(as.item(i).href); targets.push(as.item(i)); } } break; case "myspace": for (i = 0; i < as.length; i++) { var anchor = as.item(i); if( anchor.parentNode && anchor.parentNode.parentNode && (anchor.parentNode.parentNode.className.indexOf("searchResults") != -1) ) { urls.push(anchor.href); targets.push(anchor); } } break; case "youtube": underline = false; soft_wrap = true; font_size = "small"; for (i = 0; i < as.length; i++) { if (as.item(i).id.indexOf("video-long-title") == 0) { urls.push(as.item(i).href); targets.push(as.item(i)); } } break; case "wikipedia": font_size = "small"; underline = false; image_baseline = true; // include_topic = true; enable_click_tracking = su_ds.hasFeature("$titleclicktracking"); urls.push(doc.location.href); targets.push(target); break; case "flickr": underline = false; hard_wrap = true; soft_wrap = true; linked_color = "auto"; font_size = "small"; for (i = 0; i < as.length; i++) { var anchor = as.item(i); var ancestor = su_get_ancestor_by_prop_value(anchor, "className", "ResultsThumbsChild", 4); if (ancestor && anchor.firstChild && anchor.firstChild.className && (anchor.firstChild.className.indexOf("pc_img") != -1)) { urls.push(anchor.href); targets.push(anchor); } } break; case "cnn": for (i = 0; i < as.length; i++) { if (as[i].className == "cnnSearchResultsHeadline") { var redir_match = as.item(i).href.match(/arProcessing\.jsp.*?[?&]dest=([^?&]+)/); if (redir_match && redir_match.length >= 0) urls.push(redir_match[1]); else urls.push(as.item(i).href); targets.push(as.item(i)); } } break; case "cbsnews": for (i = 0; i < as.length; i++) { if (as.item(i).className == "storyTitle") { urls.push(as.item(i).href); targets.push(as.item(i)); } } break; case "cnetnews": force_inline = true; for (i = 0; i < as.length; i++) { if (as.item(i).className == "resultName") { urls.push(as.item(i).href); targets.push(as.item(i)); } } break; case "abcnews": for (i = 0; i < as.length; i++) { if (as.item(i).className == "title") { urls.push(as.item(i).href); targets.push(as.item(i)); } } break; case "msnbc": for (i = 0; i < as.length; i++) { var anchor = as.item(i); if(anchor.parentNode.tagName == "H4") { urls.push(anchor.href); targets.push(anchor); } } break; } if (urls.length == 0) return; var url = su_get_browser_url(doc); var query_detail = su_get_search_query_detail(service_id, url); var now = (new Date()).getTime(); var slstats = new Object(); slstats.timestamp = now; slstats.slq = 0; slstats.term_count = query_detail.term_count; slstats.url_count = hrefs.length; slstats.decorated_count = 0; slstats.first_decorated_num = 0; if (enable_click_tracking) { su_ds.globals.sls.push(slstats); var slq = su_ds.globals.sls.length; slstats.slq = slq; su_ds.globals.sluqh[url] = slq; var slistats = su_ds.getValue("$slistats").split(":"); for (i = 0; i < urls.length; i++) { var slt = "" + slq + su_service.getSha1(hrefs[i]); var sli = new Object(); sli.i = i; su_ds.globals.sltih[slt] = sli; if (i < 10) slistats[i] = parseInt(slistats[i]) + 1; } su_ds.setValue("$slistats", slistats.join(":")); } var context = new Object(); context.slstats = slstats; context.done = false; context.batch_count = 0; context.url_start_index = 0; context.doc = doc; context.timestamp = now; context.query_detail = query_detail; context.before_targets = before_targets; context.after_targets = after_targets; context.urls = urls; context.hrefs = hrefs; context.linked_color = linked_color; context.underline = underline; context.unlinked_color = unlinked_color; context.font_size = font_size; context.force_logo = force_logo; context.soft_wrap = soft_wrap; context.hard_wrap = hard_wrap; context.include_topic = include_topic || su_ds.getValue("$show_searchlinks_topic"); context.image_baseline = image_baseline; context.enable_click_tracking = enable_click_tracking; context.force_inline = force_inline; su_augment_links2(context); } function su_augment_links2(context) { var query = ""; if (0) //(su_ds.hasFeature("$unbatchedlinks")) { context.done = true; for (i = 0; i < context.urls.length; i++) { if (query != "") query += '%09'; query += encodeURIComponent(context.urls[i]); } } else { var url_count = 0; var i = (context.batch_count * 10); context.url_start_index = i; while ((url_count < 10) && (i < context.urls.length)) { url_count++; if (query != "") query += '%09'; query += encodeURIComponent(context.urls[i]); i++; } context.batch_count++; if (su_ds.hasFeature("$limitedlinks")) context.done = true; else context.done = (i == context.urls.length); } if (query == "") return; var params = "u=" + query; params = su_arp(params, "f", su_ds.getValue("$show_searchlinks_friends") ? 1 : 0); params = su_arp(params, "s", su_ds.getValue("$show_searchlinks_score") ? 1 : 0); params = su_arp(params, "t", su_ds.getValue("$show_searchlinks_topic") ? 1 : 0); params = su_arp(params, "m", su_ds.getValue("@dd_links_m")); params = su_arp(params, "domain", context.query_detail.domain); params = su_arp(params, "termcount", context.query_detail.term_count); params = su_arp(params, "firstpage", context.query_detail.is_first_page ? 1 : 0); params = su_arp(params, "timestamp", context.timestamp); params = su_arp(params, "batch", context.batch_count); var loc = "links.php"; if (su_ds.getValue("@dd_links_m") == "alt") loc = "test_links.php"; su_post_url_server_async( loc, params, 60000, su_augment_links_done, context); } // handles response to links.php; adds content for the links function su_augment_links_done(res) { try { if ((res.status != 200) || res.aborted) return; } catch (e) { return; } var context = res.detail; var s = ""; if (typeof(res.responseText) != "undefined") s = res.responseText; if (su_log_communication) su_log("response links.php", s); if (s == "") return; var ss; ss = s.split("\n"); var sss = ss[0].split(" "); if (sss[0] == "ERROR") return; var i; var slt; var slistats = su_ds.getValue("$slistats").split(":"); var slidfstats = su_ds.getValue("$slidfstats").split(":"); for (i = 0; i < ss.length; i++) { if (ss[i] == "") continue; var url_index = context.url_start_index + i; context.slstats.decorated_count++; if (! context.slstats.first_decorated_num) context.slstats.first_decorated_num = (i + 1); var fields = ss[i].split("\t"); var comment_level = parseInt(fields[0]); var thumbed = fields[1]; if (su_ratings[context.hrefs[url_index]]) thumbed = "1"; var score = parseInt(fields[2]); var topic = fields[3]; var friends = new Array(); var j; if (typeof(fields[4]) != "undefined" && fields[4] != "" && su_ds.getValue("$show_searchlinks_friends")) { var f = fields[4].split(","); for (j = 0; j < f.length; j++) { if (f[j] == '') continue; friends.push(f[j]); } } var comment_count = null; if (typeof(fields[5]) != "undefined" && fields[5] != "") comment_count = parseInt(fields[5]); var comment_id = null; if (typeof(fields[6]) != "undefined" && fields[6] != "") comment_id = fields[6]; var comment_text = null; if (typeof(fields[7]) != "undefined" && fields[7] != "") comment_text = fields[7].replace(/\|/g, " "); slt = ""; if (su_host.sha1 && su_ds.getValue("@enable_slstats") && context.enable_click_tracking) { slt = "" + context.slstats.slq + su_service.getSha1(context.hrefs[url_index]); var sli = su_ds.globals.sltih[slt]; var detail = new Object(); sli.detail = detail; detail.q = context.slstats.slq; detail.d = 1; detail.i = url_index; detail.dt = (thumbed) ? 1 : 0; detail.dc = (comment_count) ? comment_count : 0; detail.ds = score; detail.dl = comment_level; detail.df = friends.length; detail.dr = (comment_text) ? 1 : 0; detail.dz = (context.include_topic && (typeof(su_catnames[topic]) != "undefined")) ? 1 : 0; if (url_index < 10 && detail.df) { slistats[url_index] = parseInt(slistats[url_index]) - 1; slidfstats[url_index] = parseInt(slidfstats[url_index]) + 1; } } if (! score) score = 1; var after; var before; var after_parts = new Array(); var reviewHref = su_base_url + "url/" + su_review_url(context.urls[url_index]); // The 'float:none;padding:0;' and 'display:inline;' css rules in // here mostly cater to AOL. before = ""; if (thumbed == "1") { before = '<img border="0" width="13" height="13" style="display:inline;'; if (context.image_baseline) before += 'vertical-align:baseline;'; before += '" src="chrome://stumbleupon/content/skin/smallgreenthumbup.png"> '; } after = ''; if (context.hard_wrap) { after_parts.push("<br />"); } else if ((score <= 0) && (! su_ds.getValue("$show_searchlinks_logo"))) { after += '<span style="font-size:' + context.font_size + ';color:' + context.unlinked_color + ';float:none;padding:0;"> ·</span>'; } else { after += ' '; } after += '<a ondblclick="slu" slt="' + slt + '"'; if ((! context.include_topic) && (typeof(su_catnames[topic]) != "undefined")) { after += ' title="'; if (comment_count) { if (comment_count == 1) after += 'Read 1 review'; else after += 'Read ' + comment_count + ' reviews'; after += ' in topic ' + su_catnames[topic] + '"'; } else { after += 'See who liked this"'; } } else if (comment_count) { after += ' title="'; if (comment_count == 1) after += 'Read 1 review"'; else after += 'Read ' + comment_count + ' reviews"'; } else { after += ' title="See who liked this"'; } after += ' style="text-decoration:none;float:none;padding:0;font-size:' + context.font_size + ';color:' + context.linked_color + ';" href="' + reviewHref + '">'; var imgStyle = "display:inline;float:none;border:none;margin:0px;padding:0px;"; if (context.force_logo || su_ds.getValue("$show_searchlinks_logo")) { after += '<img ondblclick="slu" border="0" width="13" height="13" style="' + imgStyle; if (context.image_baseline) after += 'vertical-align:baseline;'; after += '" src="chrome://stumbleupon/content/skin/smallstumble.png">'; } if ((score > 0) && su_ds.getValue("$show_searchlinks_score")) { after += ' '; for (j = 0; j < score; j++) { after += '<img ondblclick="slu" border="0" width="10" height="10" style="' + imgStyle; if (context.image_baseline) after += 'vertical-align:baseline;'; after += '" src="chrome://stumbleupon/content/skin/star.png">'; } } // else if ((friends.length == 0) || // (! su_ds.getValue("$show_searchlinks_friends"))) // { // if (context.underline) // after += ' <u ondblclick="slu">Reviews</u>'; // else // after += ' Reviews'; // } if ((comment_level > 0) && su_ds.getValue("$show_searchlinks_comment_icon")) { after += ' <img ondblclick="slu" border="0" width="13" height="13" style="' + imgStyle; if (context.image_baseline) after+= 'vertical-align:baseline;'; after += '" src="chrome://stumbleupon/content/skin/smallbubble' + comment_level + '.png">'; } after += '</a>'; after_parts.push(after); after = ''; if (friends.length && su_ds.getValue("$show_searchlinks_friends")) { for (j = 0; j < friends.length; j++) { if (j == 0) { after = '<span style="text-decoration:none;float:none;padding:0;font-size:' + context.font_size + ';color:' + context.unlinked_color + ';"> · </span><a ondblclick="slp" slt="' + slt + '" style="text-decoration:none;float:none;padding:0;font-size:' + context.font_size + ';color:' + context.linked_color + ';" title="'; if (comment_text) after += comment_text; else after += friends[j] + ' likes this page'; after += '" href="' + reviewHref + '">'; after += '<img ondblclick="slp" border="0" width="13" height="13" style="' + imgStyle; if (context.image_baseline) after += 'vertical-align:baseline;'; after += '" src="chrome://stumbleupon/content/skin/smallredman.png"> '; if (context.underline) after += '<u ondblclick="slp">' + friends[j] + '</u>'; else after += friends[j]; after += '</a>'; // after_parts.push(after); } else if (j == 1) { after += '<span style="text-decoration:none;float:none;padding:0;font-size:' + context.font_size + ';color:' + context.unlinked_color + ';"> + </span>'; after += '<a ondblclick="sln" slt="' + slt + '" style="text-decoration:none;float:none;padding:0;font-size:' + context.font_size + ';color:' + context.linked_color + ';" href="' + reviewHref + '" title="' + friends[0] + ', ' + friends[1]; } else { after += ', ' + friends[j]; } } if (friends.length > 1) { after += ' like'; if (friends.length == 1) after += 's'; after += ' this page">' + (friends.length - 1) + '</a>'; } } if (context.include_topic && (typeof(su_catnames[topic]) != "undefined")) { after += '<span style="text-decoration:none;float:none;padding:0;font-size:' + context.font_size + ';color:' + context.unlinked_color + ';"> · </span><a ondblclick="slz" slt="' + slt + '" title="See related pages" style="text-decoration:none;float:none;padding:0;font-size:' + context.font_size + ';color:' + context.linked_color + ';"href="' + su_serverhttp + 'tag/' + su_catnames[topic].toLowerCase() + '/">'; if (context.underline) after += '<u ondblclick="slz">' + su_catnames[topic] + '</u>'; else after += su_catnames[topic]; after += '</a>'; } if (after != '') after_parts.push(after); var el; if (before != "") { el = context.doc.createElement("SPAN"); el.style.cssText = "white-space:nowrap!important; float:none!important; padding:0!important; text-decoration:none!important;"; el.innerHTML = before; context.before_targets[url_index].parentNode.insertBefore(el, context.before_targets[url_index]); } var after_target = context.after_targets[url_index]; if (! context.soft_wrap) after_parts = new Array(after_parts.join("")); for (j = 0; j < after_parts.length; j++) { el = context.doc.createElement("SPAN"); var cssText = "white-space:nowrap!important; float:none!important; padding:0!important; text-decoration:none!important;"; if(context.force_inline) { cssText += "display:inline!important;"; } if (context.soft_wrap) el.innerHTML = after_parts[j].replace(/ /g, " "); else el.innerHTML = after_parts[j]; if (after_target.nextSibling) after_target.parentNode.insertBefore(el, after_target.nextSibling); else after_target.parentNode.appendChild(el); after_target = el; el.style.cssText = cssText; } } if (context.enable_click_tracking) { var str = ""; var sls = su_ds.globals.sls; for (i = 0; i < sls.length; i++) { var slstats = sls[i] str += slstats.timestamp + "\t" + slstats.slq + "\t" + slstats.term_count + "\t" + slstats.url_count + "\t" + slstats.decorated_count + "\t" + slstats.first_decorated_num + "\t:"; } su_ds.setValue("$slstats", str); su_ds.setValue("$slistats", slistats.join(":")); su_ds.setValue("$slidfstats", slidfstats.join(":")); } if (! context.done) su_augment_links2(context); } function su_handle_upgrade_click(event) { var target = "https://addons.mozilla.org/firefox/138/"; su_set_location(target, null, su_new_tab(event)); su_set_visible("su_upgrade", false); } function su_handle_stumble_topic_click(event, url) { su_set_server_location( "url/" + su_review_url(url), null, su_new_tab(event)); } // Generates the topic menu function su_prepare_stumble_topic_menu(event, url) { var menuEl; if (su_ds.getValue("$stumble_topics_style") == 1) menuEl = su_get_element("su_stumble_topic_menu_right_popup") else menuEl = su_get_element("su_stumble_topic_menu_left_popup"); if (event.originalTarget != menuEl) return; if (menuEl.getAttribute("data-url") == url) return; menuEl.removeAttribute("data-url"); menuEl.setAttribute("data-url", url); // Check if a menu already exists -> If so, we need to remove it while(menuEl.childNodes.length) menuEl.removeChild(menuEl.firstChild); var url_detail = su_ds.lookup("url:url_detail", url); var item; var submenu; item = document.createElement("menu"); item.setAttribute("label", " Report a problem"); item.setAttribute("tooltiptext", "Report..."); menuEl.appendChild(item); submenu = document.createElement("menupopup"); submenu.setAttribute("id", "su_report_popup"); item.appendChild(submenu); su_prepare_reporting_menu(submenu, url_detail, false, url_detail.url); item = document.createElement("menuseparator"); menuEl.appendChild(item); item = document.createElement("menuitem"); item.setAttribute("label", "This page is about:"); item.setAttribute("tooltiptext", "Change topic to..."); item.setAttribute("style", "font-weight: bold; color: #404040;"); item.setAttribute("disabled", "true"); menuEl.appendChild(item); var stumbler_name = su_get_profile_nickname(url); if (stumbler_name) { item = document.createElement("menuitem") item.setAttribute("label", "Stumbler"); // note: actual name is 'Stumblers' if (url_detail.cur_catid == 44) { item.setAttribute("type", "checkbox"); item.setAttribute("checked", "true"); item.setAttribute("tooltiptext", "This is a stumbler profile"); item.setAttribute("oncommand", 'su_handle_recat_reset_checkbox();'); item.style.fontWeight = 'bold'; item.style.color = "#008B00"; } else { item.setAttribute("tooltiptext", "Request topic change from " + url_detail.cur_topic_name + " to Stumblers"); item.setAttribute("oncommand", 'su_handle_recat_page(event, "' + url + '", 44, "Stumbler");'); } menuEl.appendChild(item); item = document.createElement("menuitem") item.setAttribute("label", "Adult Stumbler"); if (url_detail.cur_catid == 520) { item.setAttribute("type", "checkbox"); item.setAttribute("checked", "true"); item.setAttribute("tooltiptext", "This is an adult stumbler profile"); item.setAttribute("oncommand", 'su_handle_recat_reset_checkbox();'); item.style.fontWeight = 'bold'; item.style.color = "#008B00"; } else { item.setAttribute("tooltiptext", "Request topic change from " + url_detail.cur_topic_name + " to Adult Stumbler"); item.setAttribute("oncommand", 'su_handle_recat_page(event, "' + url + '", 520, "Adult Stumbler");'); } menuEl.appendChild(item); return; } var recat_adult = su_ds.getValue("$recat_adult"); // Add list of topics var folders = new Array(); var folders_sorted = new Array(); var cats_sorted = new Array(); for (var cat in su_catnames) { if (typeof(su_topicfolders[cat]) == "undefined") continue; var folder = su_topicfolders[cat]; var name = su_catnames[cat]; if (typeof(folders[folder]) == "undefined") { folders[folder] = new Array(); folders_sorted.push(folder); cats_sorted[folder] = new Array(); } folders[folder][name]=cat; cats_sorted[folder].push(name); } folders_sorted.sort(); var nickname = su_get_profile_nickname(url); for (var i = 0 ; i < folders_sorted.length ; i++) { var folder = folders_sorted[i]; if (folder == "0") continue; // Special treatment for the "StumbleUpon news" cat var item = document.createElement("menu"); item.setAttribute("label", folder); item.setAttribute("tooltiptext", "Change topic to..."); //item.setAttribute("oncommand", // 'su_handle_stumble_topic_click(event, "' + url + '");'); menuEl.appendChild(item); var foldermenu = document.createElement("menupopup"); item.appendChild(foldermenu); cats_sorted[folder].sort(); for ( var j = 0 ; j < cats_sorted[folder].length ; j++) { var cat = cats_sorted[folder][j]; var jcatid = folders[folder][cat]; if (folder == "Adult") { if (recat_adult == 0 && nickname && jcatid != 520) continue; else if (recat_adult == 0 && jcatid != 6 && jcatid != 500) continue; else if (recat_adult == 1 && jcatid != 6 && su_ds.lookup("catid:x_flag", jcatid)) continue; } var itemCat = document.createElement("menuitem") itemCat.setAttribute("label", cat); if (jcatid == url_detail.cur_catid) { itemCat.setAttribute("type", "checkbox"); itemCat.setAttribute("checked", "true"); itemCat.setAttribute("tooltiptext", "This page is about " + url_detail.cur_topic_name); itemCat.setAttribute("oncommand", 'su_handle_recat_reset_checkbox();'); item.style.fontWeight = 'bold'; item.style.color = "#008B00"; } else { itemCat.setAttribute("tooltiptext", "Request topic change from " + url_detail.cur_topic_name + " to " + cat); itemCat.setAttribute("oncommand", 'su_handle_recat_page(event, "' + url + '", "' + jcatid + '", "' + cat + '");'); } foldermenu.appendChild(itemCat); if (jcatid == url_detail.cur_catid) { itemCat.style.fontWeight = 'bold'; itemCat.style.color = "#008B00"; } } } var catid2 = url_detail.catid2; var catid3 = url_detail.catid3; var has_cat2 = (catid2 && catid2 != url_detail.cur_catid && su_catnames[catid2] && su_catnames[catid2] != ''); var has_cat3 = (catid3 && catid3 != url_detail.cur_catid && catid3 != catid2 && su_catnames[catid3] && su_catnames[catid3] != ''); if (has_cat2 || has_cat3) { item = document.createElement("menuitem"); item.setAttribute("label", "Suggested:"); item.setAttribute("tooltiptext", "Change topic to..."); // if (has_cat2 && has_cat3) // item.setAttribute("label", "Suggested alternates:"); // else // item.setAttribute("label", "Suggested alternate:"); item.setAttribute("disabled", "true"); item.setAttribute("style", "font-weight: bold; color: #707070;"); menuEl.appendChild(item); } // Add possible choices if (has_cat2) { var itemCat = document.createElement("menuitem") itemCat.setAttribute("label", " " + su_catnames[catid2]); itemCat.setAttribute("tooltiptext", "Request topic change from " + url_detail.cur_topic_name + " to " + su_catnames[catid2]); itemCat.setAttribute("oncommand", 'su_handle_recat_page(event, "' + url + '", "' + catid2 + '", "' + su_catnames[catid2] + '");'); menuEl.appendChild(itemCat); } if (has_cat3) { var itemCat = document.createElement("menuitem") itemCat.setAttribute("label", " " + su_catnames[catid3]); itemCat.setAttribute("tooltiptext", "Request topic change from " + url_detail.cur_topic_name + " to " + su_catnames[catid3]); itemCat.setAttribute("oncommand", 'su_handle_recat_page(event, "' + url + '", "' + catid3 + '", "' + su_catnames[catid3] + '");'); menuEl.appendChild(itemCat); } } function su_handle_recat_reset_checkbox() { su_check_progress_listener(); var menuEl; if (su_ds.getValue("$stumble_topics_style") == 1) menuEl = su_get_element("su_stumble_topic_menu_right_popup") else menuEl = su_get_element("su_stumble_topic_menu_left_popup"); // Menu will be recreated menuEl.removeAttribute("data-url"); } // Handle recat of a stumble page using the topic menu function su_handle_recat_page(event, url, catid, topic_name) { su_check_progress_listener(); var detail = new Object(); detail.url = url; detail.new_catid = catid; detail.new_topic_name = topic_name; var url_detail = su_ds.lookup("url:url_detail", url); if (url_detail) { detail.old_catid = url_detail.cur_catid; detail.old_topic_name = url_detail.cur_topic_name; } else { detail.old_catid = 0; detail.old_topic_name = "unknown"; } window.openDialog( "chrome://stumbleupon/content/reportTopicDialog.xul", "", "chrome,titlebar,close,dialog,centerscreen,dependent", detail); } function su_handle_report_topic_dialog_accept(detail) { var url_detail = su_ds.lookup("url:url_detail", detail.url); url_detail.cur_catid = detail.new_catid; url_detail.cur_topic_name = detail.new_topic_name; su_change_local_catid(detail.url, detail.new_catid); var menuEl; if (su_ds.getValue("$stumble_topics_style") == 1) menuEl = su_get_element("su_stumble_topic_menu_right_popup") else menuEl = su_get_element("su_stumble_topic_menu_left_popup"); // Menu will be recreated menuEl.removeAttribute("data-url"); menuEl.setAttribute("onpopupshowing", 'su_prepare_stumble_topic_menu(event, "' + detail.url + '");'); menuEl.parentNode.setAttribute("label", detail.new_topic_name); // Tell the server to recat the page var doc = getBrowser().contentDocument; var context = new su_AsyncContext(); context.url = detail.url; context.ref_url = su_get_browser_url(doc, true); context.title = su_get_title(doc, context.ref_url); var params = ""; params = su_arp(params, "url", detail.url); params = su_arp(params, "redirect", url_detail.redirect_url); params = su_arp(params, "current", su_get_browser_url()); params = su_arp(params, "newcatid", detail.new_catid); params = su_append_sync_params(params); su_post_url_server_async( "recat.php", params, null, su_generic_done, context); su_check_progress_listener(); } function su_handle_sponsor_click(event) { var target = "sponsored_page.html"; su_set_server_location(target, null, su_new_tab(event)); } function su_handle_bug_command() { var email = "joe@stumbleupon.com"; var date = new Date(); var str; str = ""; str += "The toolbar will now open two tabs:\n\n"; str += "o The first tab will attempt to open your e-mail application.\n\n"; str += "o The second tab will display the error report. Use this if you\n"; str += " prefer to copy-and-paste into a web-based e-mail account.\n"; str += " "; var response = confirm(str); if (! response) return; str = "["; if ((stumbleid != 0) && su_ds && (su_ds.getValue("$nick") != "")) str += su_ds.getValue("$nick") + ":"; if (stumbleid != 0) str += stumbleid + "] "; str += "toolbar bug report"; var subject = str; str = "=== behavior ===\n"; str += "\n"; str += "Please describe the action(s) you performed.\n"; str += "\n"; str += "Then describe how the toolbar responded.\n"; str += "\n"; str += "Feel free to attach screenshots if applicable.\n"; str += "\n"; str += "\n"; str += "=== platform ===\n"; str += su_host.desc + "\n"; str += navigator.userAgent + "\n"; str += su_useragent + "\n"; str += date.toUTCString() + "\n"; if (su_service && (su_service._messageLog != "")) { str += "\n"; str += "\n"; str += "=== log ==="; str += su_service._messageLog; } try { str += "\n\n" + su_get_addons_desc(); } catch (e) {} var body = str; str = "mailto:" + email + "?subject="; str += encodeURIComponent(subject) + "&body="; str += encodeURIComponent(body); su_set_location(str, null, true); str = "\n TO: " + email + "\n"; str += "SUBJECT: " + subject + "\n\n\n" str += body; var filename = date.getTime() + ".txt"; su_ds.writeFile( su_ds.getResourceNSIFile("reports", filename), str); su_set_location( su_ds.getResourceURLFromName("reports", filename), null, true); } function su_get_addons_desc() { var i; var datasource = su_get_service( "@mozilla.org/extensions/manager;1", "nsIExtensionManager") .datasource; var root = su_get_rdf_resource("urn:mozilla:item:root"); var container = su_create_instance( "@mozilla.org/rdf/container;1", "nsIRDFContainer"); container.Init(datasource, root); var elements = container.GetElements(); var attributes = new Array( "name", "version", "appDisabled", "userDisabled", "internalName"); var extensions = new Array(); var themes = new Array(); while(elements.hasMoreElements()) { var element = elements.getNext(); var item = new Object(); for (i = 0; i < attributes.length; i++) { item[attributes[i]] = su_get_rdf_arc_literal( datasource, element, "http://www.mozilla.org/2004/em-rdf#" + attributes[i]); } var type_id = su_get_rdf_arc_int( datasource, element, "http://www.mozilla.org/2004/em-rdf#type"); switch (type_id) { case 2: extensions.push(item); break; case 4: themes.push(item); break; } } extensions.sort(function (a, b) { return a.name.toLowerCase() > b.name.toLowerCase(); }); themes.sort(function (a, b) { return a.name.toLowerCase() > b.name.toLowerCase(); }); var str = "=== extensions ===\n"; for (i = 0; i < extensions.length; i++) { str += extensions[i].name + " "; str += extensions[i].version; if (extensions[i].appDisabled || extensions[i].userDisabled) str += " [disabled]"; str += "\n"; } var current_theme = null; try { current_theme = su_ds.getValue("general.skins.selectedSkin"); } catch(e) {} str += "\n\n=== themes ===\n"; for (i = 0; i < themes.length; i++) { str += themes[i].name + " "; str += themes[i].version; if (themes[i].internalName == current_theme) str += " [selected]"; str += "\n"; } return str; } function su_refresh_pagemeta(from_stumblevideo_page, from) { if (su_refreshing_pagemeta) return; su_refreshing_pagemeta = true; setTimeout( su_update_pagemeta, 100, from_stumblevideo_page, from); } // Handler for when the page being viewed changes. function su_update_pagemeta(from_stumblevideo_page, from) { //!!! This needs either (a) to get some code documentation or (b) // to be refactored into several functions with descriptive // names. -- JW // Refactoring into several functions is in progress. -- JW su_refreshing_pagemeta = false; if (su_new_user) return; var doc = getBrowser().contentDocument; var new_url = su_get_browser_url(doc); var raw_url = su_get_browser_url(doc, true); var new_tld; var rateable = false; var rec_url = null; var url_detail = null; var stumblevideo = su_is_matching_domain(raw_url, "video." + su_servername); if (stumblevideo && (! from_stumblevideo_page)) su_stumblevideo_page(doc, false); try { if (! url_detail) url_detail = su_ds.lookup("url:url_detail", new_url); if (url_detail) { new_url = url_detail.url; new_tld = url_detail.tld; rateable = true; rec_url = url_detail.url; } else if (stumbleid) { new_tld = su_get_tld(new_url); rateable = su_is_url_rateable(new_url, new_tld); if (su_ds.lookup("url:from_portal_flag", new_url)) { rec_url = new_url; } else if (su_get_tld(su_get_browser_referrer_url(doc)) == su_servername) { su_ds.define("url:from_portal_flag", new_url, 1); rec_url = new_url; } } } catch (e) { su_log_error("PAGEVIEW DETAILLOOKUP", e); } if (su_promo_mode && (stumbleid == 0)) { try { su_update_website_info_promo(new_url); } catch (e) { su_log_error("PAGEVIEW INFOPROMO", e); } try { if (su_get_stumblevideo_detail()) su_set_visible("su_thumbdown", true); else su_set_visible("su_thumbdown", false); //!!! we do enable all the time to fix thet problem where sometimes the comment button doesn't get cleared? if (typeof(su_ratings[new_url]) != "undefined") su_disable_toolbar(su_ratings[new_url]); else su_enable_toolbar(); } catch (e) { su_log_error("PAGEVIEW PROMORATEBUTTONS", e); } return; } else if (stumbleid == 0) { return; } var stumbler_name = null; if ((new_tld == su_servername) || (new_tld == 'stumbleupon.com')) stumbler_name = su_get_profile_nickname(new_url); if (stumbler_name) rec_url = new_url; var non_self_stumbler = (stumbler_name && (stumbler_name != stumbleid) && (stumbler_name != su_ds.getValue("$nick"))); var browser = getBrowser().selectedBrowser; var tab_url_detail = (browser.su_url_detail) ? browser.su_url_detail : null; try { su_update_thru_domain(new_url, new_tld, url_detail, stumblevideo, false); } catch (e) { su_log_error("PAGEVIEW FAVICON", e); } try { su_update_message(tab_url_detail, url_detail, new_url, new_tld, stumblevideo); } catch (e) { su_log_error("PAGEVIEW MESSAGE", e); } try { su_update_page_feature_prompt(new_url); } catch (e) { su_log_error("PAGEVIEW FEATUREPROMPT", e); } try { su_update_firstrater(url_detail); } catch (e) { su_log_error("PAGEVIEW FIRSTRATER", e); } try { su_update_topic_and_reporting(tab_url_detail, url_detail, new_tld, false, rec_url); } catch (e) { su_log_error("PAGEVIEW TOPIC", e); } // try { // su_update_language(url_detail, false); // } catch (e) { su_log_error("PAGEVIEW LANGUAGE", e); } try { su_update_comment_level(url_detail, rateable); } catch (e) { su_log_error("PAGEVIEW COMMENT", e); } try { su_update_referral_menu_tooltip(url_detail, stumblevideo); } catch (e) { su_log_error("PAGEVIEW TOOLTIP", e); } try { su_update_thumbs(new_url, rateable, non_self_stumbler, stumblevideo, url_detail); } catch (e) { su_log_error("PAGEVIEW THUMBS", e); } try { su_update_stumbling_options(non_self_stumbler, stumbler_name); } catch (e) { su_log_error("PAGEVIEW STUMBLER", e); } try { su_update_tags(new_url) } catch (e) { su_log_error("PAGEVIEW TAGS", e); } // See if this is a tag page // only do this is text is on var tag_page = 0; var tag_name = ''; try { if (new_url.indexOf(su_base_url + "tag/") == 0) { spliturl = new_url.split("/"); if (spliturl.length > 4 && spliturl[4] != '') { tag_name = spliturl[4]; //alert("tag " + tag_name); tag_page = 1; } } if (tag_page) { // change favorites of el = su_get_element("su_cat_stumble_tags"); if (el) { el.setAttribute("label", "Through " + tag_name + "..."); el.setAttribute("oncommand", "su_select_topic('TAG_" + tag_name + "', '" + tag_name + "', false);"); el.setAttribute("tooltiptext", stumbler_name + "'s Pages"); } su_set_image("su_category", "chrome://stumbleupon/content/skin/tag.png"); } else { el = su_get_element("su_cat_stumble_tags"); if (el) { el.setAttribute("label", "Search"); el.setAttribute("oncommand", 'su_handle_mode_click(event, "Search");'); el.setAttribute("tooltiptext", "Stumble within a query"); } } } catch (e) { su_log_error("PAGEVIEW TAG", e); } try { // Reset message when we hit the message page if (new_url.indexOf("." + su_servername + "/inbox/")!=-1) { su_ds.setValue("$newmessage", false); su_set_inbox_status(''); } } catch (e) { su_log_error("PAGEVIEW INBOX", e); } setTimeout("su_reflow_toolbar(15)", 80); } function su_update_thumbs(url, rateable, non_self_stumbler, stumblevideo, url_detail) { if (stumblevideo) su_get_element("su_thumbdown").type = ""; else su_get_element("su_thumbdown").type = "menu-button"; var rating; if (rateable) rating = su_get_rating(url, stumblevideo, url_detail); else rating = null; //!!! we do enable all the time to fix thet problem where sometimes the comment button doesn't get cleared? if (rating == null) su_enable_toolbar(); else su_disable_toolbar(rating); // disable rating buttons on url pages if (rateable) { // su_get_element("su_thumbdown").disabled=false; // if the thumb isn't green, we should enable it su_get_element("su_thumbup").disabled=false; su_get_element("su_thumbdown").disabled=false; su_get_element("su_thumbup").setAttribute("onclick", su_get_element("su_thumbup").getAttribute("onclick2")); } else { // disable rating buttons su_get_element("su_thumbup").disabled=true; su_get_element("su_thumbdown").disabled=true; su_get_element("su_thumbup").setAttribute("onclick", ""); } if (su_ds.getValue("$icons") != "icons-only") { if (non_self_stumbler) su_set_label("su_thumbup", su_get_element("su_thumbup").getAttribute('showlabel2')); else su_set_label("su_thumbup", su_get_element("su_thumbup").getAttribute('showlabel')); } } function su_update_tags(new_url) { var tag_list = su_get_tag_list(new_url); if (tag_list) su_disable_tag_toolbar(tag_list); else su_enable_tag_toolbar(); } function su_update_stumbling_options(non_self_stumbler, stumbler_name) { var el; if (non_self_stumbler) { el = su_get_element("su_cat_favorites_of2"); if (el) { el.setAttribute("label", stumbler_name + "'s Favorites"); el.setAttribute("onclick", 'su_handle_mode_click(event, "' + stumbler_name + '");'); el.setAttribute("tooltiptext", stumbler_name + "'s favorites"); if (su_is_mutual_friend(stumbler_name)) el.setAttribute("image", "chrome://stumbleupon/content/skin/mutual_favorites.png"); else el.setAttribute("image", "chrome://stumbleupon/content/skin/stumbler_favorites.png"); el.setAttribute("hidden", "false"); } el = su_get_element("su_mode_stumbler"); el.setAttribute("tooltiptext", "Stumble " + stumbler_name + "'s favorites"); el.setAttribute("onclick", 'su_handle_mode_click(event, "' + stumbler_name + '");'); if (su_is_mutual_friend(stumbler_name)) su_set_image("su_mode_stumbler", "chrome://stumbleupon/content/skin/mutual_favorites.png"); else su_set_image("su_mode_stumbler", "chrome://stumbleupon/content/skin/stumbler_favorites.png"); su_set_visible("su_mode_stumbler", true); } else { el = su_get_element("su_cat_favorites_of2"); if(el) { el.setAttribute("hidden", "true"); } su_set_visible("su_mode_stumbler", (! su_ds.getValue("$show_mode_stumbler"))); } } function su_get_profile_nickname(url) { var domain = su_get_tld(url); if (domain == 'stumbleupon.com') { var spliturl = url.split("/"); var domains = spliturl[2].split("."); if (domains.length != 3) return null; if (su_ds.lookup("nickname:bad_nick_flag", domains[0])) return null; return domains[0]; } else if ((su_servername != 'stumbleupon.com') && (domain == su_servername)) { var spliturl = url.split("/"); var domains = spliturl[2].split("."); var serverparts = su_servername.split("."); if (domains.length != (serverparts.length + 1)) return null; if (su_ds.lookup("nickname:bad_nick_flag", domains[0])) return null; return domains[0]; } else { return null; } } function su_get_service_id(url, results_page_only) { if (! url.match(/(google|yahoo|ask|myspace|youtube|flickr|wikipedia|aol|cnn|bing|nytimes|cbsnews|cnet|abcnews|msnbc)/i)) return null; url = url.toLowerCase(); if (url.match(/^http.*?\/\/[^\/]*?(news\.google\.[^\.]+|news\.google\.co\.[^\.]+)\/(news.*[?&]q=)/)) return "googlenews"; else if (url.match(/^http.*?\/\/(news\.google\.[^\.]+|news\.google\.co\.[^\.]+)/)) return "googlenewsindex"; else if (url.match(/^http.*?\/\/[^\/]*?(video\.google\.[^\.]+|video\.google\.co\.[^\.]+)\/(videosearch.*[?&]q=)/)) return "googlevideo"; if (url.match(/^http.*?\/\/[^\/]*?(google\.[^\.]+|google\.co\.[^\.]+)\/((search|custom).*[?&](q|as_q)=)/)) return "google"; else if (url.match(/^http.*?\/\/[^\/]*?(google\.[^\.]+|google\.co\.[^\.]+)(\/$|webhp|#hl)/)) return "google-ajax"; else if (url.match(/^http.*?\/\/[^\/]*?(www\.ask\.com)\/(web.*[?&]q=)/)) return "ask"; else if (url.match(/^http.*?\/\/[^\/]*?(www\.bing\.com)\/(search.*?q=)/)) return "bing"; else if (url.match(/^http.*?\/\/[^\/]*?(www\.bing\.com)\/news\/(search.*?q=)/)) return "bing-news"; else if (url.match(/^http.*?\/\/[^\/]*?((search|custom)(\.)(.*(\.))?yahoo(\.).*)\/(search.*[?&]p=)/)) return "yahoo"; else if (url.match(/^http.*?\/\/[^\/]*?(search(\.)(.*(\.))?aol(\.).*)\/(search.*[?&]query=)/)) return "aol"; else if (url.match(/^http.*?\/\/[^\/]*?(searchservice\.myspace\.com)\/.*[?&]fuseaction=sitesearch\.results/)) return "myspace"; else if (url.match(/^http.*?\/\/[^\/]*?(youtube\.com)\/results.*[?&]search_query=/)) return "youtube"; else if (url.match(/^http.*?\/\/[^\/]*?flickr\.[^\.]+\/(search|.*[?&]q=)/)) return "flickr"; else if (url.match(/^http.*?\/\/[^\/]*\.wikipedia\.org\/wiki\//)) return "wikipedia"; else if (url.match(/^http:\/\/search\.cnn\.com\/search.*[?&]query=/)) return "cnn"; else if (url.match(/^http:\/\/query\.nytimes\.com\/search\/.*[?&]query=/)) return "nyt"; else if (url.match(/^http.*?\/\/(search|www)\.cbsnews\.com.*[?&]query=/)) return "cbsnews"; else if (url.match(/^http.*?\/\/news\.cnet\.com.*[?&]query=/)) return "cnetnews"; else if (url.match(/^http.*?\/\/abcnews\.go\.com.*[?&]searchtext=/)) return "abcnews"; else if (url.match(/^http:\/\/([^\.]*?\.)?msnbc\.msn\.com\/.*[?&]q=/)) return "msnbc"; else if (results_page_only) return null; else if (url.match(/^http.*?\/\/((www|news|video)\.google\.[^\.]+|(www|news|video)\.google\.co\.[^\.]+)/)) return "google"; else if (url.indexOf("http://www.ask.com") == 0) return "ask"; else if (url.indexOf("http://www.yahoo.com") == 0) return "yahoo"; else if (url.indexOf("http://www.aol.com") == 0) return "aol"; else return null; // Porting search page filters from the iebar follows the general // pattern below. Note that migrating from strings to literal regular // expressions involves changing some escaping. // else if (url.match(/^http.*?\/\/[^/]*?(URL_HOST_MATCH)/(PATH_MATCH)/)) // -- JW } function su_get_service_meta(url, results_page_only) { var service_id = su_get_service_id(url, results_page_only); if (! service_id) return null; var detail = new Object(); detail.id = service_id; switch (service_id) { case "google": case "google-ajax": case "googlevideo": case "googlenews": case "googlenewsindex": detail.name = "Google"; detail.icon = "chrome://stumbleupon/content/skin/favicon_google.png"; break; case "ask": detail.name = "Ask"; detail.icon = "chrome://stumbleupon/content/skin/favicon_ask.png"; break; case "bing": detail.name = "Bing"; detail.icon = "chrome://stumbleupon/content/skin/bubble.png"; break; case "yahoo": detail.name = "Yahoo"; detail.icon = "chrome://stumbleupon/content/skin/favicon_yahoo.png"; break; case "aol": detail.name = "AOL"; detail.icon = "chrome://stumbleupon/content/skin/favicon_aol.png"; break; case "youtube": detail.name = "YouTube"; detail.icon = "chrome://stumbleupon/content/skin/favicon_youtube.png"; break; case "flickr": detail.name = "Flickr"; detail.icon = "chrome://stumbleupon/content/skin/favicon_flickr.png"; break; default: detail = null; break; } if (detail) { detail.prompt_label = "See ratings on " + detail.name; detail.prompt_tooltip = "See who likes your " + detail.name + " search results"; } return detail; } function su_get_search_query_detail(opt_service_id, opt_url) { var url; if (opt_url) url = opt_url; else url = su_get_browser_url(); var service_id; if (opt_service_id) service_id = opt_service_id; else service_id = su_get_service_id(url, true); var detail = new Object(); detail.term_count = 0; detail.is_query_results = false; detail.is_short_query_results = false; detail.is_first_page = true; detail.domain = su_get_domain(url); detail.service_id = service_id; var query_match; var page_match; switch (service_id) { case "google": case "google-ajax": case "googlenews": case "googleindex": case "googlevideo": page_match = url.match(/[?&](start=)/); query_match = url.match(/[?&]q=([^&]*)/); break; case "ask": page_match = url.match(/[?&](page=)/); query_match = url.match(/[?&]q=([^&]*)/); break; case "bing": page_match = url.match(/[?&](first=)/); query_match = url.match(/[?&]q=([^&]*)/); break; case "yahoo": page_match = url.match(/[?&](b=)/); query_match = url.match(/[?&]p=([^&]*)/); break; case "aol": page_match = url.match(/[?&](page=)/); query_match = url.match(/[?&]query=([^&]*)/); break; } if (query_match && query_match[1]) detail.term_count = query_match[1].split("+").length; if (query_match) detail.is_query_results = true; if ((detail.term_count > 0) && (detail.term_count < 3)) detail.is_short_query_results = true; if (page_match && page_match[1]) detail.is_first_page = false; return detail; } // handles the DOMContentLoaded event function su_on_load_page(event) { var doc = event.target; var url; try { url = su_get_browser_url(doc).toLowerCase(); } catch (e) { return; } try { var win = doc.defaultView.wrappedJSObject; if (win.top != win) return; } catch (e) {} var tld = su_get_tld(url); var portal_http = false; var portal_tld = false; if (tld == su_servername) { portal_tld = true; su_attach_api(doc); su_wire_portal_links(doc); if (su_visited_login_page) su_login_page_after(); if (su_is_server_page(url, "")) { portal_http = true; // signup.php -- the page we send them to if (su_is_server_page(url, "signup.php")) su_signup_page(doc); // sign_up.php -- the page they go to if they click "Join stumbleupon" // from the web site else if (su_is_server_page(url, "sign_up.php")) su_sign_up_page(url); else if (su_is_server_page(url, "find_friends.php")) su_find_friends_page(url); else if (su_is_server_page(url, "login.php")) su_login_behavior_page(); } else if (su_is_matching_domain(url, "video." + su_servername)) { su_stumblevideo_page(doc, true); } } else if (tld == "facebook.com") { su_facebook_page(doc, url); } setTimeout(su_check_progress_listener, 0); if (stumbleid == 0) return; if (su_has_searchbox) { setTimeout(su_restore_searchbox_focus, 100); setTimeout(su_restore_searchbox_focus, 300); setTimeout(su_restore_searchbox_focus, 1000); setTimeout(su_restore_searchbox_focus, 3000); } var search_results_service_id = su_get_service_id(url, true); var search_service_id = su_get_service_id(url, false); if (search_results_service_id) su_search_results_page(doc, search_results_service_id); else if (search_service_id) su_search_service_page(doc, search_service_id); else if (portal_http) { su_portal_http_page(doc); if (url.indexOf(su_serverhttp + "tag/") == 0) su_tag_page(doc); else if (url.indexOf(su_serverhttp + "find_friends_after.php") == 0) su_find_friends_after_page(); else if (url.indexOf(su_serverhttp + "interests_after.php") == 0) su_legacy_interests_after_page(doc); else if (url.indexOf(su_serverhttp + "topic/") == 0) su_tag_page(doc); } else if (portal_tld) { var host = su_ds.getValue("$nick").toLowerCase() + "." + su_servername + "/"; var profilehttp = "http://" + host; var profilehttps = "https://" + host; if ((url.indexOf(profilehttp + "prefs/interests")==0) || (url.indexOf(profilehttps + "prefs/interests")==0)) su_interests_page(doc); else if ((url.indexOf(profilehttp + "prefs/" )==0) || (url.indexOf(profilehttps + "prefs/" )==0)) su_prefs_page(doc); } su_refresh_pagemeta(false, 7); } function su_get_debug_header() { var datasource = su_get_service( "@mozilla.org/extensions/manager;1", "nsIExtensionManager") .datasource; var root = su_get_rdf_resource("urn:mozilla:item:root"); var container = su_create_instance( "@mozilla.org/rdf/container;1", "nsIRDFContainer"); container.Init(datasource, root); var elements = container.GetElements(); var attributes = new Array( "name", "version", "appDisabled", "userDisabled"); var gm_detail = null; var ns_detail = null; while(elements.hasMoreElements()) { var element = elements.getNext(); var item = new Object(); for (i = 0; i < attributes.length; i++) { item[attributes[i]] = su_get_rdf_arc_literal( datasource, element, "http://www.mozilla.org/2004/em-rdf#" + attributes[i]); } var type_id = su_get_rdf_arc_int( datasource, element, "http://www.mozilla.org/2004/em-rdf#type"); if (type_id == 2 && item.name && item.name == "Greasemonkey") { gm_detail = new Object(); gm_detail.version = item.version; gm_detail.enabled = (item.appDisabled || item.userDisabled) ? 0 : 1; } else if (type_id == 2 && item.name && item.name == "NoScript") { ns_detail = new Object(); ns_detail.version = item.version; ns_detail.enabled = (item.appDisabled || item.userDisabled) ? 0 : 1; } if (gm_detail && ns_detail) break; } if ((! gm_detail) && (! ns_detail)) return null; var obj = new Object(); if (gm_detail) { if (su_ds.isPrefDefined("greasemonkey.enabled")) gm_detail.running = (su_ds.getValue("greasemonkey.enabled")) ? 1 : 0; var scripts = su_get_gm_scripts(); if (scripts) gm_detail.scripts = scripts; obj.greasemonkey = gm_detail; } if (ns_detail) { if (su_ds.isPrefDefined("noscript.global")) ns_detail.running = (su_ds.getValue("noscript.global")) ? 0 : 1; obj.noscript = ns_detail; } return su_ds.serialize(obj, false); } function su_get_noscript_enabled_version() { if ((typeof noscriptUtil) != "object") return false; var datasource = su_get_service( "@mozilla.org/extensions/manager;1", "nsIExtensionManager") .datasource; var root = su_get_rdf_resource("urn:mozilla:item:root"); var container = su_create_instance( "@mozilla.org/rdf/container;1", "nsIRDFContainer"); container.Init(datasource, root); var elements = container.GetElements(); var attributes = new Array( "name", "version", "appDisabled", "userDisabled"); while(elements.hasMoreElements()) { var element = elements.getNext(); var item = new Object(); for (i = 0; i < attributes.length; i++) { item[attributes[i]] = su_get_rdf_arc_literal( datasource, element, "http://www.mozilla.org/2004/em-rdf#" + attributes[i]); } var type_id = su_get_rdf_arc_int( datasource, element, "http://www.mozilla.org/2004/em-rdf#type"); if (type_id == 2 && item.name && item.name == "NoScript" && (! item.appDisabled) && (! item.userDisabled)) { return item.version; } } return null; } // // su_dotversion_compare // // Compares two version numbers of the form a.b.c.d. // Results are: // ver1 > ver2 : +1 // ver1 < ver2 : -1 // ver1 == ver2 : 0 // poorly formatted version number : null // // If they are different lengths, for example: // 1.9.3 // 1.9.3.4 // Then the longer version is considered larger. // function su_dotversion_compare(ver1, ver2) { var parts1 = ver1.split("."); var parts2 = ver2.split("."); for(var i=0; (i < parts1.length) && (i < parts2.length); i++) { var n1 = parseInt(parts1[i]); var n2 = parseInt(parts2[i]); if(isNaN(n1) || isNaN(n2)) return null; if(n1 > n2) return 1; else if(n1 < n2) return -1; } if(i == 0) return null; if(parts1.length > parts2.length) return 1; else if(parts1.length < parts2.length) return -1; else return 0; } function su_get_gm_scripts() { var file = su_get_service( "@mozilla.org/file/directory_service;1", "nsIProperties") .get("ProfD", Components.interfaces.nsILocalFile); file.append("gm_scripts"); if (! file.exists()) { file = su_ds.getChromeNSIFile("chrome://greasemonkey/content").parent; file.append("scripts"); } file.append("config.xml"); if (! file.exists()) return null; var str = su_ds.readFile(file); if (str == "") return null; var doc = su_create_instance( "@mozilla.org/xmlextras/domparser;1", "nsIDOMParser") .parseFromString(str, "text/xml"); var nodes = doc.evaluate("/UserScriptConfig/Script", doc, null, 0, null); var scripts = new Array(); var node; for (node = null; (node = nodes.iterateNext()); ) { var detail = new Object(); var i; var childNode; // detail.su = 0; // for (i = 0, childNode = null; (childNode = node.childNodes[i]); i++) // { // if (childNode.nodeName == "Include") // detail.su = (childNode.firstChild.nodeValue.toLowerCase().indexOf("stumbleupon") != -1) ? 1 : 0; // // if (detail.su) // break; // } detail.name = node.getAttribute("name"); detail.enabled = (node.getAttribute("enabled") == true.toString()) ? 1 : 0; scripts.push(detail); } return scripts; } function su_handle_prefetch_load_start() { var original_target = su_prefetcher.getCurrentTarget(); var ultimate_target = su_prefetcher.getRedirectTarget(original_target); var status = su_prefetcher.getHttpResponseStatus(original_target); if ((status == 301) || ((status == 302) && (su_get_tld(original_target) != su_get_tld(ultimate_target)))) { // The url is a permanent redirect (301) or a 302 redirect // to a different domain. su_report_redirect(url, status, ultimate_target); } } function su_report_redirect(url, status, new_target) { if (su_ds.lookup("url:reported_404_flag", url)) return; su_ds.define("url:reported_404_flag", url, 1); var context = new Object(); context.quiet = true; var params = ""; params = su_arp(params, "url", url); params = su_arp(params, "status", status); params = su_arp(params, "newurl", new_target); su_post_url_server_async( "404.php", params, 15000, su_generic_done, context); } function su_report_404(url, status) { if (su_ds.lookup("url:reported_404_flag", url)) return; su_ds.define("url:reported_404_flag", url, 1); var context = new Object(); context.quiet = true; var params = ""; params = su_arp(params, "url", url); params = su_arp(params, "status", status); su_post_url_server_async( "404.php", params, 15000, su_generic_done, context); } function su_preload_images() { var el = document.createElement("image"); var id = "su_image_loader" + su_load_image_count; su_load_image_count++; el.setAttribute("id", id); el.setAttribute("src", "chrome://stumbleupon/content/skin/arrow_green-b.png"); el.setAttribute("style", "visibility:hidden;border:0px solid black;width:0px;height:0px;"); } function su_handle_resource_installed(event) { var el = document.createElement("image"); var id = "su_image_loader" + su_load_image_count; su_load_image_count++; el.setAttribute("src", su_ds.getResourceURLFromSourceURL(event.URL)); el.setAttribute("id", id); el.setAttribute("style", "visibility:hidden;border:0px solid black;width:0px;height:0px;"); el.setAttribute("onload", 'su_handle_resource_image_load(event, "' + event.URL + '", "' + id + '");'); el.setAttribute("onerror", 'su_handle_resource_image_load(event, "' + event.URL + '", "' + id + '");'); document.getElementById("main-window").appendChild(el); } function su_handle_resource_image_load(event, source_url, testid) { var iconpic_regex = new RegExp("^http://cdn.stumble-upon.com/iconpics/(\\d*)\\.jpg$"); var iconpic_match = source_url.match(iconpic_regex); var favicon_regex = new RegExp("^http://cdn.stumble-upon.com/images/stumblethru/(.*\\.ico)$"); if (su_test_stumblethru_update) favicon_regex = new RegExp("^" + su_serverhttp + "images/stumblethru/(.*\\.ico)$"); var favicon_match = source_url.match(favicon_regex); var searchlinks_regex = new RegExp("^http://cdn.stumble-upon.com/images/(.*searchlinks.*_prompt.gif)$"); var searchlinks_match = source_url.match(searchlinks_regex); if (iconpic_match) { var contactid = iconpic_match[1]; var contact = su_ds.selectRow("contact", "contactid", contactid); if (event.type == "load") { if (contact) { contact.iconpic = su_get_time_s(); su_ds.updateRow(contact); su_refresh_referral_menu(9); } } else { if (contact) { contact.iconpic = 0; su_ds.updateRow(contact); } su_ds.deleteFile( su_ds.getResourceNSIFile("iconpics", contactid + ".jpg")); } } else if (searchlinks_match) { var filename = searchlinks_match[1]; if (event.type == "load") { if (su_searchlinks_dialog_detail) { var detail = su_searchlinks_dialog_detail; su_searchlinks_dialog_detail = null; su_handle_searchlinks_dialog_resource_load(detail); } } else { su_ds.setValue("$shown_searchlinks_dialog", false); su_ds.setValue("$show_searchlinks_score", false); su_ds.setValue("$show_searchlinks_friends", false); su_ds.setValue("$show_searchlinks_topic", false); su_ds.flushPrefs(); su_ds.deleteFile( su_ds.getResourceNSIFile("images", filename)); if (su_searchlinks_dialog_detail) { var detail = su_searchlinks_dialog_detail; su_searchlinks_dialog_detail = null; if (detail.stumble) stumble(stumble.new_tab, true); } } } else if (favicon_match) { if (event.type == "load") { su_refresh_dyn_channels(); } else { var filename = favicon_match[1]; su_ds.deleteFile( su_ds.getResourceNSIFile("favicons", filename)); } } var el = document.getElementById(testid); el.parentNode.removeChild(el); } // in Firefox 1.5+, this observer service listener detects application // event, like uninstalling the toolbar or quitting the application var su_host_observer = { observe : function(subject,topic,data) { subject = subject.QueryInterface(Components.interfaces.nsIUpdateItem); if ((topic == "em-action-requested") && (subject.name == "StumbleUpon") && (data == "item-uninstalled")) { su_handle_em_uninstall(); } } } // each window's load() registers an event_observer; when a window // invokes an event using invoke_global_event(), the observerService // dispatches a notification to each event_observer var su_event_observer = { observe : function (subject, topic, data) { var detail = null; if (data && data != "") detail = su_ds.deserialize(data); switch (topic) { case "su_login": var skip_cookies = (detail && detail.skip_cookies); var ignore_cookies = (detail && detail.ignore_cookies); var new_profile = (detail && detail.new_profile); var new_user_prompt = (detail && detail.new_user_prompt); su_login(skip_cookies, ignore_cookies, new_profile, new_user_prompt); break; case "su_logout": su_logout(); break; case "su_change-password": su_change_password(); break; case "su_configure-toolbar": var from_preference_dialog = (detail && detail.from_preference_dialog); su_configure_toolbar(from_preference_dialog); break; case "su_referral-menu-dirty": su_referral_menu_dirty = true; break; case "su_update-referral-menu": su_update_referral_menu(); break; case "su_refresh-category-selector": su_refresh_category_selector(); break; case "su_dyn-channels-dirty": su_dyn_channels_dirty = true; break; case "su_update-dyn-channels": su_update_dyn_channels(); break; case "su_schedule-remove-data": su_schedule_remove_data(); break; case "su_message-button-click": su_handle_message_button_click(subject); break; } } } function su_verify_cookie_perms(notify_upon_modify) { if (! su_ds.isPrefDefined("network.cookie.cookieBehavior") || !su_ds.getValue("@auto_cookie_exceptions")) return; var supr_domain = su_ds.getValue("@supr_domain"); var domains = new Array(su_servername, "video." + su_servername, supr_domain); var perm_man = su_get_service( "@mozilla.org/permissionmanager;1", "nsIPermissionManager"); var modified = false; if (su_ds.getValue("network.cookie.cookieBehavior") != 0) { modified = true; var i; for (i = 0; i < domains.length; i++) { var nsiuri = su_get_nsiuri(domains[i]); perm_man.add(nsiuri, "cookie", perm_man.ALLOW_ACTION); } } if (modified && notify_upon_modify) { setTimeout(su_alert_cookie_change, 100); } } function su_alert_cookie_change() { var ps = su_get_service( "@mozilla.org/embedcomp/prompt-service;1", "nsIPromptService"); ps.alert(window, "StumbleUpon", "Exceptions to allow StumbleUpon cookies have been added.\n\n" + "This is required for the StumbleUpon toolbar to be fully functional.\n\n"); } function su_gui_render() { var test_ids = [ "su_render", "su_overflow_popup", "su_stumble_topic", "su_page_feature_prompt", "su_messages", "firstrater", "su_searchbox", "su_category", "su_referral_menu", "su_website_info", "su_thumbdown", "su_thumbup", // "su_inbox-count", "su_referred", "su_stumble", "su_splitter_first_flexbox", "su_spacer"]; // keep trying until we find the gui var i; for (i = 0; i < test_ids.length; i++) { if (! su_get_element(test_ids[i])) { setTimeout("su_gui_render()", 100); return; } } // if ((su_get_element("su_render") == null) || // (su_get_element("su_category") == null)) // { // setTimeout("su_gui_render()", 100); // return; // } su_set_visible("su_bug", su_enable_message_log); // These configure toolbars correctly when opening a new browser // window after changing toolbar elements but before persisting. // There may be a better way to handle this, by figuring out how // to persist without breaking urlbar; for now it works. -- JW // try { // su_prevent_toolbar_sharing(); // } catch (e) { su_log_error("INIT SHARING", e); } try { su_refresh_toggle_button(true); } catch (e) { su_log_error("INIT TOGGLE", e); } // Netscape 8.0.x needs a separator to push the stumble button past // the NS logo. if (su_host.netscape && (su_host.version.indexOf("8.0") != -1)) su_get_element("su_spacer").collapsed = false; try { su_verify_cookie_perms(su_new_install); } catch (e) { su_log_error("ALLOW COOKIES", e); } if (su_new_install) { var loc = "firefox_start.php"; if (su_host.dist) loc = "campus_start.php"; su_set_server_location(loc, null, true); try { // block popups from external applications ( a major new source of unwanted popups ) // Only do this once, in case they have a reason to set it back su_ds.setValue("privacy.popups.disable_from_plugins", 2); } catch (e) { su_log_error("PREPARE BROWSER", e); } } else if (su_new_upgrade && (su_private_label.indexOf("ALPHA") != 0) && (su_private_label.indexOf("BETA") != 0)) { su_new_upgrade = false; } su_new_install = false; su_dist_time(); var installed = su_ds.getIntValue("@installed"); var now_s = su_get_time_s(); // if ((now_s - installed) > (3600 * 24)) // su_promo_mode = true; if (stumbleid == 0) { su_move_toolbar(true, 2); su_configure_toolbar(false); su_check_progress_listener(); } else { su_show_searchlinks_dialog(false, false, false); su_load_data2(false); // calls configure_toolbar() } if (window.onViewToolbarsPopupShowing) { // This is a bit tricky. Basically, we're replacing a browser- // defined function with our own function. For details, see the // comments in function // su_replacement_onViewToolbarsPopupShowing. window.su_saved_onViewToolbarsPopupShowing = window.onViewToolbarsPopupShowing; window.onViewToolbarsPopupShowing = window.su_replacement_onViewToolbarsPopupShowing; } if (window.BrowserCustomizeToolbar) { // This is a bit tricky. Basically, we're replacing a browser- // defined function with our own function. For details, see the // comments in function // su_replacement_onViewToolbarsPopupShowing. window.su_saved_BrowserCustomizeToolbar = window.BrowserCustomizeToolbar; window.BrowserCustomizeToolbar = window.su_replacement_BrowserCustomizeToolbar; } if (window.BrowserToolboxCustomizeDone) { // This hack is similar to the one above. See function // su_replacement_BrowserToolboxCustomizeDone. window.su_saved_BrowserToolboxCustomizeDone = window.BrowserToolboxCustomizeDone; var toolbox = document.getElementById("navigator-toolbox"); toolbox.customizeDone = window.su_replacement_BrowserToolboxCustomizeDone; } if (window.foxytunesSetFoxyTunesPosition) { window.su_saved_foxytunesSetFoxyTunesPosition = window.foxytunesSetFoxyTunesPosition; window.foxytunesSetFoxyTunesPosition = window.su_replacement_foxytunesSetFoxyTunesPosition; } window.addEventListener("resize", su_handle_window_resize, false); window.addEventListener("focus", su_handle_window_focus, true); // for instances where we still need a load listener (such as interests_after.php) window.addEventListener("DOMContentLoaded", su_on_load_page, true); getBrowser().addEventListener("click", su_handle_content_click, false); // We may have to do this if onLocationChange stops working. // if (su_host.ff2plus) // getBrowser().tabContainer.addEventListener("TabSelect", su_handle_tabselect, false); su_gui_initialized = true; su_ds.prefRetries = 15; setTimeout("su_reflow_toolbar(3);", 0); setTimeout("su_reflow_toolbar(3);", 500); setTimeout("su_cleanup_toolbox(true, false)", 550); setInterval("su_process_quarter_hourly()", 15 * 60 * 1000); } // We may have to do this if onLocationChange stops working. //function su_handle_tabselect(event) //{ // su_refresh_pagemeta(false, 11); //} function su_photoBlogContext() { if (gContextMenu) { menuitem = su_get_element('context-photoblog-ilikeit'); if (menuitem) { menuitem.hidden = !gContextMenu.onImage; //alert("photo " + !gContextMenu.onImage); } // menuitem = su_get_element('context-photoblog-notforme'); // if(menuitem) // menuitem.hidden = !gContextMenu.onImage; // look for selected text var selectedText = su_getSelectedText(" "); // alert("?" + selectedText); if (selectedText != "") { // tag button //!!! only do this if size isn't greater than maximum tag size... menuitem = su_get_element('context-stumble-tagit'); menuitem.hidden = false; var selectedText2 = selectedText; if (selectedText2.length > 15) selectedText2 = selectedText.substring(0, 15) + "..."; menuitem.label = "Tag this page as '" + selectedText2 + "'"; menuitem.setAttribute("class", "menuitem-iconic"); menuitem.setAttribute("image", "chrome://stumbleupon/content/skin/tag.png"); // search //!!! only do this if absolute enable_search == yes //!!! We've stopped prompting for enable_search, so we'll leave // it as is for now. menuitem = su_get_element('context-stumble-search'); menuitem.hidden = false; selectedText2 = selectedText; if (selectedText2.length > 15) selectedText2 = selectedText.substring(0, 15) + "..."; menuitem.label = "StumbleThru '" + selectedText2 + "'"; menuitem.setAttribute("class", "menuitem-iconic"); menuitem.setAttribute("image", "chrome://stumbleupon/content/skin/stumble.png"); } else { menuitem = su_get_element('context-stumble-tagit'); menuitem.hidden = true; menuitem = su_get_element('context-stumble-search'); menuitem.hidden = true; } } } function su_contextTag() { var current_url = su_get_browser_url(); var selectedText = su_getSelectedText(" "); su_get_element("su_searchbox").value = selectedText; su_tagit(current_url, selectedText, 0, su_get_title(), su_get_browser_url(null, true)); } function su_contextSearch(event) { var selectedText = su_getSelectedText(" "); su_old_search = selectedText; su_visited_searchbox = 1; su_get_element('su_searchbox').removeAttribute("mode"); if (su_url_has_tag) { su_url_has_tag = false; su_get_element('su_searchbox').value = ''; su_get_element('su_searchbox').removeAttribute("mode"); su_get_element("su_tag").image="chrome://stumbleupon/content/skin/tag.png"; su_get_element('su_tag').setAttribute("tooltiptext", su_get_element('su_tag').getAttribute("tooltiptext2")); su_get_element("su_tag2").image="chrome://stumbleupon/content/skin/tag.png"; su_get_element('su_tag2').setAttribute("tooltiptext", su_get_element('su_tag2').getAttribute("tooltiptext2")); } var searchbox = su_get_element("su_searchbox"); searchbox.value = selectedText; if (! (searchbox.hasAttribute("focused") && (searchbox.getAttribute("focused") == "true"))) { searchbox.focus(); } var new_tab = su_new_tab(event); new_tab = new_tab || su_ds.getValue("$search_new_window"); su_stumble_in_tag(selectedText, new_tab); } function su_getSelectedText(concationationChar) { var node = document.popupNode; var selection = ""; if ((node instanceof HTMLTextAreaElement) || (node instanceof HTMLInputElement && node.type == "text")) { selection = node.value.substring(node.selectionStart, node.selectionEnd); } else { var focusedWindow = new XPCNativeWrapper(document.commandDispatcher.focusedWindow, 'document', 'getSelection()'); selection = focusedWindow.getSelection().toString(); } // Limit length to 150 to optimize performance. Longer does not make sense if (selection.length>=150) selection = selection.substring(0, 149); selection = selection.replace(/(\n|\r|\t)+/g, " "); // Strip spaces at start and end. selection = selection.replace(/(^\s+)|(\s+$)/g, ""); selection = selection.split(" "); // Remove certain characters at the beginning and end of every word for (i=0; i<selection.length; i++) { selection[i]=selection[i].replace(/^(\&|\(|\)|\[|\]|\{|\}|"|,|\.|!|\?|'|:|;)+/, ""); selection[i]=selection[i].replace(/(\&|\(|\)|\[|\]|\{|\}|"|,|\.|!|\?|'|:|;)+$/, ""); } selection = selection.join(concationationChar); return selection; } function su_show_banner(prompt, icon, accept_callback, decline_callback) { var box = getBrowser().getNotificationBox(); var notification = box.getNotificationWithValue("su_message"); if (notification) return; var buttons = new Array(); buttons.push({ label: "Join StumbleUpon Now", accessKey: "J", popup: null, callback: accept_callback}); buttons.push({ label: "No thanks", accessKey: "N", popup: null, callback: decline_callback}); buttons.push({ label: "Later", accessKey: "L", popup: null, callback: function(){}}); const priority = box.PRIORITY_WARNING_MEDIUM; box.appendNotification( prompt, "su_prompt", icon, priority, buttons); } function su_handle_prompt_click(prompt, button_name, detail) { if (button_name == "accept") { su_verify_cookie_perms(false); var params = ""; var loc = "sign_up.php"; params = su_arp(params, "version", su_useragent); if (su_host.dist) loc = su_arp(loc, "dist", su_host.dist, true); if (su_ds.getValue("@facebook_user")) loc = su_arp(loc, "pre", "facebook", true); loc = su_arp(loc, "pre2", prompt, true); params = su_arp(params, "post_url", detail.post_url); su_set_server_location( loc, params, detail.new_tab); } else if ((button_name == "decline") && (prompt == "prompt1")) { su_ds.setValue("@enable_prompt1", false); } else if ((button_name == "decline") && (prompt == "prompt2")) { su_ds.setValue("@enable_prompt2", false); } } // handles the window load event function su_handle_window_load() { if (! su_login_initialized) { setTimeout(su_handle_window_load, 1000); return; } if (stumbleid != 0) { if ((su_get_browser_window_count() == 1) && su_ds.getValue("$autologout")) su_logout_auth(); else su_load_data1(false); } // we need to wait until the gui is rendered before we do most things setTimeout("su_gui_render()", 100); // Initialize photoblog context menu var menu = su_get_element("contentAreaContextMenu"); menu.addEventListener("popupshowing", su_photoBlogContext, false); } // handles the window unload event function su_handle_window_unload() { try { // To avoid a memory leak, this block needs to run per XUL window. // -- JW var observer_service = su_get_service( "@mozilla.org/observer-service;1", "nsIObserverService"); observer_service.removeObserver(su_http_observer, "http-on-modify-request"); observer_service.removeObserver(su_http_observer, "http-on-examine-response"); observer_service.removeObserver(su_host_observer, "em-action-requested"); observer_service.removeObserver(su_event_observer, "su_login"); observer_service.removeObserver(su_event_observer, "su_logout"); observer_service.removeObserver(su_event_observer, "su_change-password"); observer_service.removeObserver(su_event_observer, "su_configure-toolbar"); observer_service.removeObserver(su_event_observer, "su_referral-menu-dirty"); observer_service.removeObserver(su_event_observer, "su_update-referral-menu"); observer_service.removeObserver(su_event_observer, "su_dyn-channels-dirty"); observer_service.removeObserver(su_event_observer, "su_update-dyn-channels"); observer_service.removeObserver(su_event_observer, "su_refresh-category-selector"); observer_service.removeObserver(su_event_observer, "su_schedule-remove-data"); observer_service.removeObserver(su_event_observer, "su_message-button-click"); var processed_ids = new Object(); while (su_persist_queue.length) { // Doing document.persist can break the urlbar, so we do it upon // window close (ref: Firefox 2RC1). -- JW var id = su_persist_queue.pop(); if (processed_ids[id]) continue; processed_ids[id] = true; document.persist(id, "currentset"); } if (su_get_browser_window_count() == 0) su_handle_last_browser_window_unload() } catch (e) {} } function su_handle_last_browser_window_unload() { var i; if (su_ds.getValue("@clear_favicons")) { su_ds.setValue("@clear_favicons", false); var channels = su_ds.getThruDomainChannels(false); if (channels) { for (i = 0; i < channels.length; i++) { su_ds.deleteResource( "favicons", su_get_channel_id(channels[i].domain) + ".ico"); } } } if (su_is_uninstall_scheduled()) { su_remove_searchplugin(); } else if(!su_remove_data_scheduled) { var ids = su_ds.getValue("@id_list").split(":"); for (i = 0; i < ids.length; i++) { if (ids[i] == "") continue; stumbleid = ids[i]; if (su_ds.getUserPrefValue(ids[i], "$search_clear_queries")) { // If they've elected to clear queries, remove them. su_queries = new Array(); su_store_queries(); } } if (su_preference_dialog) su_preference_dialog.cancelDialog(); if ((stumbleid != 0) && su_ds.getValue("$autologout")) su_logout(); su_ds.flushPrefs(); } if (su_remove_data_scheduled) su_remove_data(); } // used by the window unload listener to determine whether the // extension has been scheduled to be uninstalled function su_is_uninstall_scheduled() { var root; if (su_uninstall_scheduled) { // In Firefox 1.5+, we use the su_uninstall_observer to detect a // scheduled uninstallation. -- JW return true; } else { try { root = su_get_rdf_resource("urn:mozilla:extension:root"); } catch (e) { // This datasource has been renamed in Firefox 1.5+ and no // longer features the toBeUninstalled arcs. -- JW return false; } } // [kudos:] This is derived from the FirefoxView extension by Alex // Sirota. -- JW var container = su_get_service( "@mozilla.org/rdf/container;1", "nsIRDFContainer"); var extension_ds = su_get_service( "@mozilla.org/extensions/manager;1", "nsIExtensionManager") .datasource; try { container.Init(extension_ds, root); } catch (e) { return false; } var found = false; var elements = container.GetElements(); while (elements.hasMoreElements()) { var element = elements.getNext(); var name = su_get_rdf_arc_literal( extension_ds, element, "http://www.mozilla.org/2004/em-rdf#name"); var to_be_uninstalled = su_get_rdf_arc_literal( extension_ds, element, "http://www.mozilla.org/2004/em-rdf#toBeUninstalled"); if ((to_be_uninstalled == "true") && (name == "StumbleUpon")) found = true; } return found; } // if the extension is scheduled to be uninstalled, the window unload // listener calls this routine to uninstall the search plugin function su_remove_searchplugin() { // [kudos:] This is derived from the SearchPluginHacks extension by // Alex Sirota. -- JW var i; var searchbar = su_get_element('searchbar'); if (! searchbar) return; var searchbar_popup = document.getAnonymousElementByAttribute( searchbar, 'anonid', 'searchbar-popup'); var menuitems = searchbar_popup.getElementsByTagName("menuitem"); var menuitem = null; for (i = 0; i < menuitems.length; i++) { if (menuitems[i].label == "StumbleUpon") { menuitem = menuitems[i]; break; } } if (! menuitem) return; var plugin_uri = unescape(menuitem.value); var plugin_path; if (plugin_uri.indexOf("engine://") == 0) plugin_path = plugin_uri.substr(9); else su_log_error("SEARCHPLUGIN URI FORMAT ERROR", plugin_uri); var image_uri = unescape(menuitem.getAttribute('src')); var image_path; if (image_uri.indexOf("file:///") == 0) { var handler = su_create_instance( "@mozilla.org/network/protocol;1?name=file", "nsIFileProtocolHandler"); image_path = handler.getFileFromURLSpec(image_uri).path; } else { su_log_error("SEARCHPLUGIN IMAGE URI FORMAT ERROR", image_uri); } try { su_ds.deleteFile(su_ds.getFileFromPath(plugin_path)); su_ds.deleteFile(su_ds.getFileFromPath(image_path)); } catch (e) {} try { if (typeof(searchbar_popup.hidePopup) == "function") searchbar_popup.hidePopup(); menuitem.parentNode.removeChild(menuitem); } catch (e) {} } // handles the window click event function su_handle_window_mousedown(event) { if (! su_has_searchbox) return true; // su_recent_platform_ctrl_key_state = (su_host.mac) ? event.metaKey : event.ctrlKey; if (! event.target.id) return; switch (event.target.id) { case "su_searchbox": su_keep_searchbox_focus = true; break; case "su_stumble": case "su_category": case "su_thumbup": case "su_thumbdown": case "su_website_info": case "su_tag": case "su_tag2": break; default: su_keep_searchbox_focus = false; break; } return true; } // handles the window focus event function su_handle_window_focus(event) { if (! su_has_searchbox) return true; if (su_keep_searchbox_focus && event.target.location && (event.target.location.href == "chrome://browser/content/browser.xul")) { setTimeout(su_restore_searchbox_focus, 100); } else if (su_keep_searchbox_focus && event.target.id && (event.target.id == "content")) { setTimeout(su_restore_searchbox_focus, 100); } } // restores the searchbox function su_restore_searchbox_focus() { if (su_keep_searchbox_focus) { var searchbox = su_get_element("su_searchbox"); if (! (searchbox.hasAttribute("focused") && (searchbox.getAttribute("focused") == "true"))) searchbox.focus(); } } // handles the window keypress event; see also handle_window_keyup function su_handle_window_keypress(event) { // su_recent_platform_ctrl_key_state = (su_host.mac) ? event.metaKey : event.ctrlKey; var str = ""; if (event.altKey) str += "Alt+"; if (event.ctrlKey) str += "Ctrl+"; if (event.metaKey) str += "Command+"; if (event.shiftKey) str += "Shift+"; su_recent_keypress_modifiers = str; return true; } // handles the window keyup event using commands defined by // refresh_keybindings(); note that we need both a keypress listener // and a keyup listener because the former gives us modifiers and the // latter gives us keyCodes that distinquish between the numeric // keypad w/ numlock on and the number row function su_handle_window_keyup(event) { var keyid; if (event.charCode) keyid = su_keyids_by_eventkeycode[event.charCode]; else keyid = su_keyids_by_eventkeycode[event.keyCode]; var keyspec = su_recent_keypress_modifiers + keyid; if (su_commands_by_keyspec[keyspec]) su_commands_by_keyspec[keyspec].doCommand(); return true; } function su_move_to_bookmark_bar() { su_ds.setValue("@toolbar-position", "PersonalToolbar"); su_ds.setValue("@position-group", "first"); su_move_toolbar(true, 9); } // called by the global configure-toolbar event and during init to // move the top-level toolbar elements function su_move_toolbar(force, from) { var toolbar_position = su_ds.getValue("@toolbar-position"); var position_group = su_ds.getValue("@position-group"); var toolbar = su_get_element(toolbar_position); var toolbaritem; var new_parent; var popup; if (! toolbar) { toolbar_position = "stumbleupon"; position_group = "first"; su_ds.setValue("@toolbar-position", toolbar_position); su_ds.setValue("@position-group", position_group); toolbar = su_get_element(toolbar_position); su_ds.flushPrefs(); } if (force && (toolbar.tagName == "toolbar") && window.BrowserCustomizeToolbar && ((position_group == "first") || (position_group == "last"))) { var splitter = su_get_element("su_right-justify-splitter"); if (splitter) splitter.collapsed = true; // If we don't hide the popup, the menu gets munged if we move the // toolbar somewhere else. popup = su_get_element("su_stumble_popup"); if (typeof(popup.hidePopup) == "function") popup.hidePopup(); if (su_overflow_popup_open) { popup = su_get_element("su_overflow_popup"); if (typeof(popup.hidePopup) == "function") popup.hidePopup(); } new_parent = su_get_element("su_container"); new_parent.hidden = true; // su_dp("moving to hbox"); su_move_toolbar_elements(new_parent, null, 1); var toolbars = document.getElementsByTagName("toolbar"); var target_index = -1; var prev_index = -1; var i; // First, find the toolbar locations for (i = 0; i < toolbars.length; i++) { if(su_is_item_in_toolbox(false, "su_toolbaritem", toolbars[i])) { prev_index = i; if(target_index != -1) break; } if (! toolbars[i].hasAttribute("customizable")) continue; if (toolbars[i].getAttribute("customizable").toLowerCase() != "true") continue; if (toolbars[i].id == toolbar_position) { target_index = i; if(prev_index != -1) break; } } if(target_index != -1) { // Add it to the new su_place_toolbaritem(toolbars[target_index], position_group); // Remove it from the old if(target_index != prev_index) { try { su_is_item_in_toolbox(true, "su_toolbaritem", toolbars[prev_index]); } catch (e) {}; } } if((target_index == -1) && (toolbar_position != "status-bar")) { // If we didn't find a valid (customizable) toolbar parent, then force our // toolbar to the default location. toolbar_position = "stumbleupon"; position_group = "first"; su_ds.setValue("@toolbar-position", toolbar_position); su_ds.setValue("@position-group", position_group); toolbar = su_get_element(toolbar_position); su_place_toolbaritem(toolbar, position_group); su_ds.flushPrefs(); } } toolbaritem = su_get_element("su_toolbaritem"); var drop = false; var new_bar; if ((toolbar_position == "status-bar") || (toolbar_position == "yahoo-toolbar")) { new_parent = su_get_element(toolbar_position); new_bar = new_parent; } else if (toolbaritem) { new_bar = toolbaritem.parentNode; var drop = true; if (su_is_element_on_bar(false, "gtbToolbar", "su_toolbaritem")) { toolbar_position = "gtbToolbar"; new_parent = su_get_element("gtbToolbar"); // su_dp("toolbaritem is on gtbToolbar", new_parent.id); position_group = "first"; if (toolbaritem.hasAttribute("flex")) toolbaritem.removeAttribute("flex"); toolbaritem.setAttribute("width", 0); su_ds.setValue("@toolbar-position", toolbar_position); } else { new_parent = su_get_element("su_toolbar_container"); try { position_group = "drop"; toolbar_position = su_get_parent_toolbar_id(new_parent); } catch (e) { //!!! This is a failsafe case that gets hit by some seamonkey // 1.1 and Firefox 2.0.0.2 users. if ((toolbar_position == "stumbleupon") && (position_group == "first")) su_log_error("MOVE ERROR1", e); else su_log_error("MOVE FAILSAFE1", e, toolbar_position, position_group); toolbar_position = "stumbleupon"; position_group = "first"; new_parent = su_get_element("su_container"); new_bar = new_parent.parentNode; new_parent.hidden = false; } su_ds.setValue("@toolbar-position", toolbar_position); su_ds.setValue("@position-group", position_group); } } else if (toolbar_position == "stumbleupon") { new_parent = su_get_element("su_container"); position_group = "first"; su_ds.setValue("@toolbar-position", toolbar_position); su_ds.setValue("@position-group", position_group); new_bar = new_parent.parentNode; new_parent.hidden = false; } else { // su_dp("no toolbaritem"); new_parent = su_get_element(toolbar_position); new_bar = new_parent; } // If the selected toolbar is missing, use the default location. if (! new_parent) { // su_dp("no new parent"); toolbar_position = "stumbleupon"; position_group = "first"; su_ds.setValue("@toolbar-position", toolbar_position); su_ds.setValue("@position-group", position_group); new_parent = su_get_element("su_container"); new_bar = new_parent.parentNode; force = true; } // if force, then make sure the toolbar they are moving to is not hidden if (force) { new_bar.hidden = false; new_bar.collapsed = false; } var hidden_state = ! su_ds.getValue("@toolbar-visible"); if (toolbar_position == "stumbleupon") { su_get_element("stumbleupon").collapsed = hidden_state; } else { su_get_element("stumbleupon").collapsed = true; if (hidden_state) { // su_dp("hidden"); // To hide the toolbar elements, we move them to the collapsed // toolbar. -- JW if (toolbaritem) { if (toolbaritem.hasAttribute("flex")) toolbaritem.removeAttribute("flex"); toolbaritem.setAttribute("width", 0); } toolbar_position = "stumbleupon"; new_parent = su_get_element("su_container"); } } var old_parent = su_get_element("su_splitter_first_flexbox").parentNode; if ((toolbar_position == su_old_toolbar_position) && (position_group == su_old_toolbar_position_group) && (old_parent.id != "su_container")) { setTimeout( function (win) { win.su_cleanup_toolbox(true, false); }, 0, window); su_init_splitters(); return; } /* if (toolbaritem) { if (toolbaritem.hasAttribute("width")) toolbaritem.removeAttribute("width"); if (! toolbaritem.hasAttribute("flex")) toolbaritem.setAttribute("flex", 1); } */ su_bookmarks_sibling_loc = null; su_old_toolbar_position = toolbar_position; su_old_toolbar_position_group = position_group; su_moving_toolbar = true; // If we don't hide the popup, the menu gets munged if we move the // toolbar somewhere else. popup = su_get_element("su_stumble_popup"); if (typeof(popup.hidePopup) == "function") popup.hidePopup(); if (su_overflow_popup_open) { popup = su_get_element("su_overflow_popup"); if (typeof(popup.hidePopup) == "function") popup.hidePopup(); } if (toolbar_position == "stumbleupon") { su_toolbar_justification = "left"; // su_dp("id", su_get_parent_toolbar_id(new_parent)); su_move_toolbar_elements(new_parent, null, 2); // The following contains workarounds to fix the bug where the // toolbar appears 150px tall in old browsers (ref: Netscape 7.2, // XP and Firefox 1.0RC1, XP) -- JW if (new_parent.parentNode.boxObject.height > 100) { su_get_element("su_field").style.height = "32px"; new_parent.style.height = "32px"; new_parent.parentNode.style.height = "32px"; } new_parent.hidden = false; } else if (toolbar_position == "gtbToolbar") { // su_dp("moving toolbar to gtbToolbar", new_parent.id); su_toolbar_justification = "left"; hbox = document.createElement("hbox"); hbox.setAttribute("id", "su_googlebar_container"); new_parent.insertBefore(hbox, new_parent.firstChild); hbox.__defineSetter__("collapsed", function() {}); new_parent = hbox; su_move_toolbar_elements(new_parent, null, 3); } else if ((position_group == "last") || (position_group == "drop")) { var sibling; if (position_group == "drop") { // su_dp("survey"); try { su_survey_toolbar_siblings(toolbaritem); sibling = toolbaritem.previousSibling; } catch (e) { if ((toolbar_position == "stumbleupon") && (position_group == "first")) su_log_error("MOVE ERROR2", e); else su_log_error("MOVE FAILSAFE2", e, toolbar_position, position_group); su_ds.setValue("@toolbar-position", "stumbleupon"); su_ds.setValue("@position-group", "first"); su_ds.setValue("@toolbar-visible", true); } } else { sibling = new_parent.lastChild; } if ((toolbar_position == "PersonalToolbar") && (position_group == "last")) su_toolbar_justification = "right"; else su_toolbar_justification = (su_test_previous_sibling_flexibility(sibling)) ? "right" : "left"; // su_dp("justification", su_toolbar_justification); if (su_toolbar_justification == "left") { if (old_parent.id != "su_toolbar_container") su_move_toolbar_elements(new_parent, null, 4); } else if (su_toolbar_justification == "right") { if ((old_parent.id == "su_toolbar_container") && (su_ds.getValue("@toolbar-position") != "status-bar")) { if ((old_parent.parentNode.id != new_parent.id) && (position_group == "last")) new_parent.appendChild(old_parent); } else { if (position_group == "last") { var hbox; if (su_ds.getValue("@toolbar-position") == "status-bar") hbox = su_get_element("su_statusbar_container"); else hbox = su_get_element("su_otherbar_container"); if (! hbox) { hbox = document.createElement("hbox") if (su_ds.getValue("@toolbar-position") == "status-bar") hbox.setAttribute("id", "su_statusbar_container"); else hbox.setAttribute("id", "su_otherbar_container"); hbox.setAttribute("flex", "1"); new_parent.appendChild(hbox); } new_parent = hbox; } su_move_toolbar_elements(new_parent, null, 5); var outer_container = su_get_toolbar_outer_container(); var width = outer_container.boxObject.width; width = su_ds.getPrefValue("@right-justify-width", width); outer_container.setAttribute("width", width + "px"); if (outer_container.hasAttribute("flex")) outer_container.removeAttribute("flex"); if (su_bookmarks_sibling_loc) setTimeout(su_move_toolbar_bookmarks, 1000, new_parent); } } } else { su_toolbar_justification = "left"; su_move_toolbar_elements(new_parent, new_parent.firstChild, 6); } su_moving_toolbar = false; // change state of mozilla suite menuitem var menuitem = su_get_element("view_stumble_menuitem"); if (menuitem) { if (hidden_state) menuitem.removeAttribute("checked"); else menuitem.setAttribute("checked", "true"); } setTimeout( function (win) { win.su_cleanup_toolbox(true, false); }, 0, window); su_init_splitters(); } function su_verify_toolbar_move(from) { if (su_get_element("su_stumble")) return; // If we can't find the stumble button, recover upon browser // restart. su_log_error( "MOVE FAILSAFE4", new Object(), from, su_ds.getValue("@toolbar-position"), su_ds.getValue("@position-group")); su_ds.setValue("@toolbar-position", "stumbleupon"); su_ds.setValue("@position-group", "first"); if (from == 5) { setTimeout(alert, 50, "StumbleUpon cannot accommodate this new configuration.\n\n" + "Please restart the browser to recover from this error.\n\n"); } else if (from == 6) { setTimeout(alert, 50, "The specified toolbar movement cannot be completed.\n\n" + "Please restart the browser to recover from this error.\n\n"); } } function su_place_toolbaritem(toolbar, position_group) { var currents; if ((typeof toolbar.currentSet) == "string") currents = toolbar.currentSet.split(","); else if (toolbar.hasAttribute("currentset")) currents = toolbar.getAttribute("currentset").split(","); else currents = new Array(); if (position_group == "first") { if ((toolbar.id == "toolbar-menubar") && (currents[0] == "menubar-items")) { currents.splice(1, 0, "su_toolbaritem"); var previous = su_get_element("menubar-items"); if (previous) { try { toolbar.insertItem( "su_toolbaritem", previous.nextSibling, null, false); } catch (e) { su_log("PLACE ERROR1", toolbar.id, position_group); } } else { try { toolbar.insertItem( "su_toolbaritem", toolbar.firstChild, null, true); } catch (e) { su_log("PLACE ERROR2", toolbar.id, position_group); } } } else { currents.splice(0, 0, "su_toolbaritem"); try { toolbar.insertItem( "su_toolbaritem", toolbar.firstChild, null, true); } catch (e) { su_log("PLACE ERROR3", toolbar.id, position_group); } } } else if (position_group == "last") { currents.push("su_toolbaritem"); toolbar.insertItem( "su_toolbaritem", null, null, false); } toolbar.setAttribute("currentset", currents.join(",")); su_persist_queue.push(toolbar.id); } function su_move_toolbar_bookmarks(container) { var width = su_ds.getValue("@right-justify-width"); container.setAttribute("width", width + "px"); if (container.hasAttribute("flex")) container.removeAttribute("flex"); setTimeout(su_reflow_toolbar, 1000, 4); } function su_get_parent_toolbar_id(el) { var toolbar = su_get_parent_toolbar(el); if (toolbar) return toolbar.id; else return null; } function su_get_parent_toolbar(el) { var depth = 0; while ((el.tagName != "toolbar") && (el.tagName != "statusbar")) { depth++; if (depth == 1000) { break; } el = el.parentNode; } if (depth == 1000) { su_log_error("PARENT FIND", ((el && el.id) ? el.id : ("no id " + (typeof el))), su_ds.getValue("@toolbar-position"), su_ds.getValue("@position-group")); su_ds.setValue("@toolbar-position", "stumbleupon"); su_ds.setValue("@position-group", "first"); su_ds.setValue("@toolbar-visible", true); return null; } return el; } function su_survey_toolbar_siblings(outer_container) { su_bookmarks_sibling_loc = null; if (! outer_container) return; var sibling = outer_container.parentNode.firstChild; var seen_container = false; while (sibling) { if (! sibling.id) continue; if (sibling == outer_container) seen_container = true; if (sibling.id == "personal-bookmarks") { su_bookmarks_sibling_loc = (seen_container) ? "right" : "left"; break; } sibling = sibling.nextSibling; } } // used by move_toolbar() to determine whether any previous sibling // of the toolbar is a flexible element; if one is, then the toolbar // is right-justified function su_test_previous_sibling_flexibility(previous_sibling) { var sibling = previous_sibling; var regexp = new RegExp("^spring\\d+$"); var found_flexible_element = false; while (sibling) { if (sibling.hasAttribute("flex") || (sibling.id && (sibling.id.search(regexp) == 0))) { found_flexible_element = true; break; } sibling = sibling.previousSibling; } return found_flexible_element; } // moves the top-level toolbar elements from // su_splitter_first_flexbox through either su_site-box-count or // su_overflow_menu to a new location subsequent to argument // target_next_sibling function su_move_toolbar_elements(target_parent, target_next_sibling, from) { try { // throw("t"); var sibling = su_get_element("su_splitter_first_flexbox"); var previous_sibling_id = ""; var old_parent = sibling.parentNode; // su_dp("move elements", old_parent.id, target_parent.id, from); var depth = 0; while (previous_sibling_id != "su_overflow_menu") { depth++; if (depth == 1000) { break; } previous_sibling_id = sibling.id; var element = sibling; sibling = sibling.nextSibling; var new_element; if ((element.id == "su_stumble_menu") || (element.id =="su_category") || (element.id == "su_field") || (element.id == "su_referral_menu") || (element.id == "su_overflow_menu")) { new_element = element; } else { new_element = element.cloneNode(true); element.parentNode.removeChild(element); } if (target_next_sibling) target_parent.insertBefore(new_element, target_next_sibling); else target_parent.appendChild(new_element); if (new_element.id == "su_field") { var width = su_ds.getValue("@search-width"); new_element.setAttribute("width", width + "px"); } } if (depth == 1000) { su_log_error("MOVE LOOP", from, su_ds.getValue("@toolbar-position"), su_ds.getValue("@position-group")); su_ds.setValue("@toolbar-position", "stumbleupon"); su_ds.setValue("@position-group", "first"); su_ds.setValue("@toolbar-visible", true); } if ((old_parent.id == "su_statusbar_container") && (target_parent.id != "su_statusbar_container")) old_parent.parentNode.removeChild(old_parent); if ((old_parent.id == "su_googlebar_container") && (target_parent.id != "su_googlebar_container")) old_parent.parentNode.removeChild(old_parent); if ((old_parent.id == "su_otherbar_container") && (target_parent.id != "su_otherbar_container")) old_parent.parentNode.removeChild(old_parent); } catch (e) { su_log_error("MOVE TOOLBAR", e, from, su_ds.getValue("@toolbar-position"), su_ds.getValue("@position-group")); su_ds.setValue("@toolbar-position", "stumbleupon"); su_ds.setValue("@position-group", "first"); su_ds.setValue("@toolbar-visible", true); } } function su_refresh_toggle_button(force) { if (! window.BrowserCustomizeToolbar) return; var visible = su_ds.getValue("@toolbar_toggle_visible"); var found = false; found = su_is_item_in_toolbox((force && (! visible)), "su_toggle"); if (! force) su_ds.setValue("@toolbar_toggle_visible", found); if (force && (! found) && visible) su_add_toggle_button(); } function su_add_toggle_button() { if (document.getElementById("su_toggle")) return; var urlbar = su_get_element("urlbar-container"); var target = null; if (urlbar) target = urlbar.parentNode; if (target && target.collapsed) target = null; var preferred_target = (target) ? true : false; if (! target) target = su_get_element("nav-bar"); if (target && target.collapsed) target = null; if (! target) target = su_get_element("toolbar-menubar"); if (target && target.collapsed) target = null; if (target && target.hasAttribute("customizable") && (target.getAttribute("customizable").toLowerCase() == "true")) { var currents = target.currentSet.split(","); if (preferred_target) { var i; for (i = 0; i < currents.length; i++) { if (currents[i] == "urlbar-container") { currents.splice(i, 0, "su_toggle"); break; } } target.insertItem("su_toggle", urlbar, null, false); } else { currents.push("su_toggle"); target.insertItem("su_toggle", null, null, false); } target.setAttribute("currentset", currents.join(",")); su_persist_queue.push(target.id); } else { su_ds.setValue("@toolbar_toggle_visible", false); } } function su_is_item_in_toolbox(remove, id, opt_toolbar) { var toolbars; if (opt_toolbar) { toolbars = new Array(); toolbars.push(opt_toolbar); } else { toolbars = document.getElementsByTagName("toolbar"); } var found = false; var i; for (i = 0; i < toolbars.length; i++) { var item = su_get_element(id); if (remove) su_is_element_on_bar(true, toolbars[i].id, id); if (! toolbars[i].hasAttribute("customizable")) continue; if (! toolbars[i].getAttribute("customizable").toLowerCase() == "true") continue; var currents; if ((typeof toolbars[i].currentSet) == "string") currents = toolbars[i].currentSet.split(","); else currents = new Array(); var new_currents = new Array(); while(currents.length) { if (currents[0] == id) { found = true; if (remove) currents.shift(); else new_currents.push(currents.shift()); } else { new_currents.push(currents.shift()); } } var current_set = new_currents.join(","); var old_set; if (toolbars[i].hasAttribute("currentset")) old_set = toolbars[i].getAttribute("currentset"); else old_set = ""; toolbars[i].setAttribute("currentset", current_set); if (current_set != old_set) su_persist_queue.push(toolbars[i].id); } return found; } function su_is_element_on_bar(remove, toolbar_id, id) { // This works around a browser bug where el.parentNode.id can report // the wrong id when parentNode is a toolbar (ref: Firefox 2.0rc1, // Linux). -- JW var toolbar = su_get_element(toolbar_id); if (! toolbar) return false; var found = false; var sibling = toolbar.firstChild; var count = 0; var el; while (sibling) { count++; if (count == 1000) { break; } el = sibling; sibling = sibling.nextSibling; if (el.id == id) { found = true; if (remove) toolbar.removeChild(el); } } if (count == 1000) su_log_error("ON LOOP"); return found; } // this is part of a hack that redefines behavior of the view-> // toolbars->StumbleUpon menuitem in Firefox-derived browsers function su_replacement_onViewToolbarsPopupShowing(event) { // During initialization, we make // window.su_saved_onViewToolbarsPopupShowing point to the browser- // defined function window.onViewToolbarsPopupShowing (ref Firefox // 1.5). Then we make window.onViewToolbarsPopupShowing point to // this function. So this function runs when the browser invokes // window.onViewToolbarsPopupShowing(..). // // This function executes the original browser-defined routine // before locating and modifying the StumbleUpon Toolbar menuitem. // -- JW window.su_saved_onViewToolbarsPopupShowing(event); var sibling = event.target.firstChild; var found = false; while (sibling) { if (sibling.getAttribute("label").indexOf("StumbleUpon Toolbar") == 0) { found = true; break; } sibling = sibling.nextSibling; } if (found) { var menuitem = sibling; menuitem.setAttribute("checked", su_ds.getValue("@toolbar-visible")); menuitem.removeEventListener("command", onViewToolbarCommand, false); menuitem.addEventListener("command", su_handle_view_toolbar_command, false); } } function su_replacement_BrowserCustomizeToolbar() { var toolbars = document.getElementsByTagName("toolbar"); var i; var found = false; for (i = 0; i < toolbars.length; i++) { if (toolbars[i].hasAttribute("currentset")) { var currents = toolbars[i].getAttribute("currentset").split(","); var j; for (j = 0; j < currents.length; j++) { if (currents[j] == "su_toolbaritem") { found = true; break; } } } } if (! found) { var item = su_get_element("su_toolbaritem"); var toolbar = su_get_element("stumbleupon"); toolbar.setAttribute("currentset", "su_toolbaritem"); toolbar.insertItem("su_toolbaritem", null, null, true); su_persist_queue.push("stumbleupon"); } setTimeout("su_replacement_BrowserCustomizeToolbar2();", 200); var position = su_ds.getValue("@toolbar-position"); if ((position == "status-bar") || (position == "yahoo-toolbar")) return; var el = su_get_element("bookmarks-ptf"); if (el) el.hidden = true; var new_parent = su_get_element("su_container"); new_parent.hidden = true; var splitter = su_get_element("su_right-justify-splitter"); if (splitter) splitter.collapsed = true; su_move_toolbar_elements(new_parent, null, 7); var needs_cleanup = false; var container = su_get_element("su_googlebar_container"); if (container) { needs_cleanup = true; container.parentNode.removeChild(container); } var toolbaritem = su_get_element("su_toolbaritem"); if (toolbaritem) { needs_cleanup = true; if (toolbaritem.hasAttribute("width")) toolbaritem.removeAttribute("width"); if (toolbaritem.hasAttribute("flex")) toolbaritem.removeAttribute("flex"); } if (needs_cleanup) su_cleanup_toolbox(true, true); } function su_replacement_BrowserCustomizeToolbar2() { window.su_saved_BrowserCustomizeToolbar(); var position = su_ds.getValue("@toolbar-position"); if ((position == "status-bar") || (position == "yahoo-toolbar")) { su_get_element("stumbleupon").collapsed = true; su_get_element("su_toolbar_customize_label").value = ""; } else { var shortcut = su_ds.getValue("$shortcut_toolbar"); var label = "StumbleUpon Toolbar Items"; if (shortcut != "") { label += " (" + su_get_display_keyspec(shortcut) + ")"; } su_get_element("stumbleupon").collapsed = false; su_get_element("su_toolbar_customize_label").value = label; } } function su_replacement_BrowserToolboxCustomizeDone(aToolboxChanged) { if (window.su_saved_BrowserToolboxCustomizeDone) window.su_saved_BrowserToolboxCustomizeDone(aToolboxChanged); su_refresh_toggle_button(false); var position = su_ds.getValue("@toolbar-position"); if ((position == "status-bar") || (position == "yahoo-toolbar")) return; var el = su_get_element("bookmarks-ptf"); if (el) el.hidden = false; var outer_container = su_get_element("su_toolbaritem"); if (outer_container) { setTimeout(su_replacement_BrowserToolboxCustomizeDone2, 0); } else { su_get_element("stumbleupon").collapsed = true; var toolbar = su_get_element("stumbleupon"); var currents = toolbar.currentSet.split(","); currents.push("su_toolbaritem"); toolbar.setAttribute("currentset", currents.join(",")); toolbar.insertItem("su_toolbaritem", null, null, true); su_ds.setValue("@toolbar-visible", false); su_persist_queue.push("stumbleupon"); } if (su_customize_invoked_from_preference_dialog) { su_customize_invoked_from_preference_dialog = false; setTimeout(su_preferences, 1000); } su_get_element("su_toolbar_customize_label").value = ""; } function su_replacement_BrowserToolboxCustomizeDone2() { su_move_toolbar(false, 5) su_reflow_toolbar(5); setTimeout(su_verify_toolbar_move, 0, 5); } function su_replacement_foxytunesSetFoxyTunesPosition() { try { su_saved_foxytunesSetFoxyTunesPosition(); } catch (e) {} setTimeout(su_replacement_BrowserToolboxCustomizeDone2, 200); } function su_is_toolbar_shared() { var toolbar = su_get_element("stumbleupon"); var sibling = toolbar.firstChild; var count = 0; var el; while (sibling) { count++; if (count == 1000) break; el = sibling; sibling = sibling.nextSibling; switch (el.id) { case "su_toolbaritem": case "stringbundleset": case "bundle_stumble": case "su_commandset": case "su_keyset": case "su_container": case "su_render": break; default: return true; } } return false; } function su_prevent_toolbar_sharing() { if (! window.BrowserCustomizeToolbar) return; var toolbar = su_get_element("stumbleupon"); var currents = toolbar.currentSet.split(","); var new_currents = new Array(); var i; var modified = false; var el; for (i = 0; i < currents.length; i++) { switch (currents[i]) { case "__empty": case "su_toolbaritem": new_currents.push(currents[i]); break; default: modified = true; break; } } var sibling = toolbar.firstChild; var count = 0; while (sibling) { count++; if (count == 1000) { break; } el = sibling; sibling = sibling.nextSibling; switch (el.id) { case "su_toolbaritem": case "stringbundleset": case "bundle_stumble": case "su_commandset": case "su_keyset": case "su_container": case "su_render": break; default: toolbar.removeChild(el); } } if (count == 1000) su_log_error("SHARING LOOP"); if (modified) { var new_parent = su_get_element("stumbleupon-hbox"); new_parent.hidden = true; su_move_toolbar_elements(new_parent, null, 8); toolbar.setAttribute("currentset", currents.join(",")); su_persist_queue.push("stumbleupon"); setTimeout("su_move_toolbar(false, 3);", 0); setTimeout(su_reflow_toolbar, 0, 6); } } function su_customize_toolbox() { su_customize_invoked_from_preference_dialog = true; document.getElementById("cmd_CustomizeToolbars").doCommand(); } // forwards the view->toolbars menuitem command event in Firefox- // derived browsers function su_handle_view_toolbar_command(event) { setTimeout("su_toggle_toolbar();", 0); } // ultimately called by the view->toolbars menuitem in Firefox- // derived browsers function su_toggle_toolbar() { su_toggling_toolbar = true; var toolbar_position = su_ds.getValue("@toolbar-position"); var new_visible_state; if (toolbar_position == "stumbleupon") new_visible_state = su_get_element("stumbleupon").collapsed; else new_visible_state = ! su_ds.getValue("@toolbar-visible"); su_ds.setValue("@toolbar-visible", new_visible_state); su_move_toolbar(false, 4); su_toggling_toolbar = false; if (new_visible_state) su_reflow_toolbar(7); /* if (su_new_install && (! su_ds.getValue("@shown_toolbar"))) { su_ds.setValue("@shown_toolbar", true); stumble(0); } */ su_ds.flushPrefs(); } // handles the mousedown event for the splitter to the right of the // search box function su_handle_splitter_search_right_mousedown(event) { su_moving_splitter = true; var outer_container = su_get_element("su_toolbaritem"); if (outer_container || (su_toolbar_justification == "right")) su_shorten_toolbar_to_element("su_splitter_search_right"); su_set_toolbar_element_widths(su_get_element("su_stumble")); return true; } // handles the mouseup event for the splitter to the right of the // search box function su_handle_splitter_search_right_mouseup(event) { setTimeout('su_remove_toolbar_element_widths(su_get_element("su_stumble"))', 0); su_moving_splitter = false; if (su_get_element("su_field").boxObject.width > 400) setTimeout('su_get_element("su_field").setAttribute("width", "400px")'); setTimeout("su_refresh_splitters(false)", 0); return true; } function su_get_toolbar_outer_container() { var position = su_ds.getValue("@toolbar-position"); var container; if ((position == "status-bar") && (su_ds.getValue("@position-group") == "last")) { container = su_get_element("su_statusbar_container"); } else if (su_ds.getValue("@position-group") == "last") { container = su_get_element("su_otherbar_container"); } else if (position == "gtbToolbar") { container = su_get_element("su_googlebar_container"); } if (! container) { container = su_get_element("su_stumble").parentNode; } if (container.id == "su_toolbar_container") { container = su_get_element("su_toolbaritem"); } return container; } // handles the mouseup event for the dynamic splitter that's created // when the toolbar is right-justified function su_handle_right_justify_splitter_mousedown(event) { su_moving_splitter = true; su_shorten_toolbar_to_element("su_thumbdown"); su_set_toolbar_element_widths(su_get_toolbar_outer_container()); return true; } // handles the mousedown event for the dynamic splitter that's // created when the toolbar is right-justified function su_handle_right_justify_splitter_mouseup(event) { var hbox = su_get_toolbar_outer_container(); su_ds.setValue("@right-justify-width", hbox.boxObject.width); setTimeout('su_remove_toolbar_element_widths(su_get_element("' + hbox.id + '"))', 0); su_moving_splitter = false; setTimeout("su_refresh_splitters(false)", 0); return true; } // used by splitter mousedown listeners to set temporary minwidths // for adjacent elements function su_set_toolbar_element_widths(sibling) { sibling = sibling.parentNode.firstChild; while (sibling != null) { if (sibling.id == "personal-bookmarks") { var el = su_get_element("bookmarks-stack"); if (el) el.hidden = true; } else if (sibling.id && (sibling.id.indexOf("spring") != 0) && (sibling.id != "su_splitter_first_flexbox") && (sibling.id != "su_field") && (sibling.id != "su_toolbar_container") && (sibling.id != "su_toolbaritem") && (sibling.id != "su_statusbar_container") && (sibling.id != "su_otherbar_container") && (sibling.id != "su_googlebar_container") && (sibling.tagName != "tooltip") && (! sibling.hasAttribute("flex"))) { if (sibling.hasAttribute("minwidth")) sibling.setAttribute("su_savedminwidth", sibling.getAttribute("minwidth")); if (sibling.hasAttribute("width")) sibling.setAttribute("su_hadwidth", "true"); sibling.setAttribute("minwidth", sibling.boxObject.width + "px"); } sibling = sibling.nextSibling; } } // used by splitter mouseup listeners to remove the temporary // minwidths set by set_toolbar_element_widths function su_remove_toolbar_element_widths(sibling) { sibling = sibling.parentNode.firstChild; while (sibling != null) { if (sibling.hasAttribute("su_savedminwidth")) sibling.setAttribute("minwidth", sibling.getAttribute("su_savedminwidth")); else sibling.removeAttribute("minwidth"); if (sibling.id == "personal-bookmarks") { var el = su_get_element("bookmarks-stack"); if (el) { el.hidden = false; } } else if ((sibling.id != "su_splitter_first_flexbox") && (sibling.id != "su_field") && (sibling.id != "su_toolbar_container") && (sibling.id != "su_toolbaritem") && (sibling.id != "su_statusbar_container") && (sibling.id != "su_otherbar_container") && (sibling.id != "su_googlebar_container") && (sibling.tagName != "tooltip")) { if (sibling.hasAttribute("su_hadwidth")) sibling.removeAttribute("su_hadwidth"); else sibling.removeAttribute("width"); } sibling = sibling.nextSibling; } } function su_shorten_toolbar_to_element(stop_id) { var popup = su_get_element("su_overflow_popup"); var i; var item; for (i = 0; i < popup.childNodes.length; i++) { item = popup.childNodes[i]; if (item.id && (item.id == stop_id)) return; } var container = su_get_element("su_stumble").parentNode; var menuified_one = false; for (i = container.childNodes.length - 2; i >= 0; i--) { item = container.childNodes[i]; if (item.id && (item.id == stop_id)) break; su_menuify_toolbar_element(item); menuified_one = true; } if (menuified_one) { var menu = su_get_element("su_overflow_menu"); menu.collapsed = false; menu.hidden = false; } su_cleanup_overflow_flexbox() } // handles the left margin splitter mousedown event function su_handle_splitter_first_mousedown(event) { su_moving_splitter = true; return true; } // handles the left margin splitter mouseup event function su_handle_splitter_first_mouseup(event) { su_moving_splitter = false; setTimeout("su_refresh_splitters(false)", 0); return true; } // handles the sidebar splitter mouseup event function su_handle_sidebar_mouseup(event) { setTimeout("su_refresh_splitters(false)", 0); return true; } // handles the sidebar splitter attr modified event function su_handle_sidebar_attr_modified(event) { if (event.attrName == "hidden") setTimeout("su_refresh_splitters(false)", 0); return true; } // queues a change to the hidden state of a top-level toolbar element function su_set_visible(id, state) { state = ! state; var element = su_get_element(id); var changed = false; if (element.parentNode.id == "su_overflow_popup") { if (element.hasAttribute("savedhidden")) element.setAttribute("savedhidden", state); else element.collapsed = state; } else { if (element.hasAttribute("su_ismode")) { changed = (element.hidden != state); element.hidden = state; } else { changed = (element.collapsed != state); element.collapsed = state; } } if ((! state) && (id == "su_referred")) setTimeout(su_stop_referred_throbber, su_ds.getValue("$referral_throbber_interval_ms")) if (changed) setTimeout("su_reflow_toolbar(8)", 10); } function su_stop_referred_throbber() { su_set_attribute("su_referred", "busy", "false"); } // for future use, to fix the textonly bug //function su_is_toolbar_textonly() //{ // var toolbar = su_get_parent_toolbar(su_get_element("su_stumble")); // if (! toolbar) // return false; // // if (toolbar.hasAttribute("mode") && // (toolbar.getAttribute("mode") == "text")) // return true; //} // queues a change to the label of a top-level toolbar element function su_set_label(id, str) { var element = su_get_element(id); var menuified = (element.parentNode.id == "su_overflow_popup"); if (id == "su_mode") { su_get_element("su_mode_label").collapsed = (! su_get_label_visibility(id, menuified)); return; } else if (id == "su_category") { str += " "; } // When str is null, use the value in the showlabel attribute. // -- JW if (su_get_label_visibility(id, menuified)) { if ((! str) && element.hasAttribute("showlabel")) str = element.getAttribute("showlabel"); } else { str = ""; } var changed = (element.label != str); str = (str) ? str : ""; if (str == "") { if (menuified) element.className = "su-hidetext-menuified"; else element.className = "su-hidetext"; } else { if (menuified) element.className = "su-showtext-menuified"; else { if ((element.id == "su_category") || (element.id == "su_stumble_topic")) element.className = "su-hideicon-showtext"; else element.className = "su-showtext"; } element.label = str; } if (changed) setTimeout("su_reflow_toolbar(9)", 10); } function su_set_attribute(id, attr_name, value) { var el = su_get_element(id); if (! el) return; el.setAttribute(attr_name, value); } function su_remove_attribute(id, attr_name, value) { var el = su_get_element(id); if (! el) return; if (el.hasAttribute(attr_name)) el.removeAttribute(attr_name); } // used by the toolbar refresh routines to determine whether the // label associated with a top-level toolbar element is to be // displayed when it has the specified menuified state function su_get_label_visibility(id, menuified) { var always_visible_ids = ",su_login,su_start,su_referred,su_site-count-box,su_recthumbup,su_category,su_stumble_topic," + "su_stumble_topic_menu_left,su_stumble_topic_menu_right," + "su_page_feature_prompt,su_grab,su_approve,su_idx,su_tld,"; var text_icons_mode_visible_ids = ",su_stumble,su_thumbup,su_profile," + "su_friends,su_referral_menu,firstrater,su_sponsor," + "su_mode,su_stumble_menu,su_website_info,"; var element = su_get_element(id); var query = "," + id + ","; if ((stumbleid != 0) && su_ds.getValue("$show_firstrater_label_always")) always_visible_ids += "firstrater,su_sponsor,"; if (su_promo_mode && (stumbleid == 0)) always_visible_ids += "su_referral_promo,su_website_info_promo,su_sites_promo,su_video_promo," var text_icons = true; if (stumbleid != 0) text_icons = (su_ds.getValue("$icons") == "text-icons"); // Visible if: // (1) it's always visible // (2) we're configured to text-icons, and this is in the visible subset // (3) it's in the overflow popup, and it has a showlabel attribute // -- JW return (always_visible_ids.indexOf(query) != -1) || (text_icons && (text_icons_mode_visible_ids.indexOf(query) != -1)) || (menuified && element.hasAttribute("showlabel") && (id != "su_mode")); } // queues a change to the image of a top-level toolbar element function su_set_image(id, uri) { var element = su_get_element(id); var changed = (element.image != uri); if (changed) { element.image = uri; setTimeout("su_reflow_toolbar(10)", 10); } } // used by splitter mouseup handlers and the splitter init routine to // set splitter visibility and to store new state function su_refresh_splitters(use_saved_latch_state) { try { var content_x = su_get_element("content").boxObject.x; var toolbar_x = su_get_element("su_stumble").boxObject.x; var sidebar_hidden = su_get_element("sidebar-splitter").hidden || su_get_element("sidebar-box").collapsed; var align_with_content = su_ds.getValue("@latch-to-sidebar"); var splitter_first = su_get_element("su_splitter_first"); var first_flexbox = su_get_element("su_splitter_first_flexbox"); var splitter = su_get_element("su_right-justify-splitter") if ((su_toolbar_justification == "left") && (splitter)) { splitter.parentNode.removeChild(splitter); } else if ((su_toolbar_justification == "right") && (! splitter)) { var splitter = document.createElement("splitter"); splitter.setAttribute("id", "su_right-justify-splitter"); splitter.setAttribute("class", "su_splitter"); splitter.setAttribute("state", "open"); splitter.setAttribute("collapse", "none"); splitter.setAttribute("resizebefore", "grow"); splitter.setAttribute("resizeafter", "closest"); splitter.setAttribute("onmousedown", "return su_handle_right_justify_splitter_mousedown(event);"); splitter.setAttribute("onmouseup", "return su_handle_right_justify_splitter_mouseup(event);"); var sibling = su_get_toolbar_outer_container(); sibling.parentNode.insertBefore(splitter, sibling); } else if ((su_toolbar_justification == "right") && (splitter)) { splitter.collapsed = false; var sibling = su_get_toolbar_outer_container(); sibling.parentNode.insertBefore(splitter, sibling); } // Determine whether the toolbar should be latched to the sidebar. if (su_is_toolbar_shared()) { align_with_content = false; splitter_first.collapsed = true; } else if (su_ds.getValue("@toolbar-position") == "stumbleupon") { splitter_first.collapsed = sidebar_hidden; if (! use_saved_latch_state) { if ((su_sidebar_was_hidden == sidebar_hidden) && (su_old_toolbar_x != toolbar_x)) { var latch_to_sidebar = su_ds.getValue("@latch-to-sidebar"); if (latch_to_sidebar) align_with_content = (toolbar_x >= (content_x - 20)); else align_with_content = (first_flexbox.boxObject.width > 20); } su_ds.setValue("@latch-to-sidebar", align_with_content); } } else { align_with_content = false; splitter_first.collapsed = true; } var new_width; if (align_with_content) { // If latched, move the toolbar to match. if (sidebar_hidden) { new_width = 0; } else { // This hidden statement works around an apparent browser bug // (ref: Firefox 2.0.0.2, Linux). -- JW splitter_first.hidden = false; new_width = content_x - first_flexbox.boxObject.x - splitter_first.boxObject.width; if (new_width < 0) new_width = 0; } } else { new_width = 0; } first_flexbox.setAttribute("width", new_width + "px"); var search = su_get_element("su_field"); if (! search.collapsed) { var width = search.boxObject.width; if (width != 0) { // The zero test above fixes an issue where the search box // width gets set to zero upon toggling visibility (ref: // Firefox 1.5, XP). -- JW su_ds.setValue("@search-width", width); } } su_old_toolbar_x = su_get_element("su_stumble").boxObject.x; su_sidebar_was_hidden = sidebar_hidden; su_reflow_toolbar(11); if (su_bookmarks_sibling_loc) su_reflow_bookmarks_toolbar(); } catch (e) { su_log_error("REFRESH SPLITTERS", e, su_ds.getValue("@toolbar-position"), su_ds.getValue("@position-group")); } } // handles the window resize event function su_handle_window_resize(event) { var width = window.innerWidth; if (width != su_resize_window_width) { su_resize_window_width = width; su_reflow_toolbar(12); } else if (! su_resize_window_dirty) { // handles window maximize case su_resize_window_dirty = true; setTimeout(su_handle_window_resize2, 500); } return true; } function su_handle_window_resize2() { if (! su_resize_window_dirty) return; su_reflow_toolbar(14); su_resize_window_dirty = false; } function su_reflow_toolbar(from) { try { if (! su_gui_initialized) return; // Nuke the flexbox. var flexbox = su_get_element("su_overflow_flexbox"); if (flexbox) flexbox.parentNode.removeChild(flexbox); var container = su_get_element("su_stumble").parentNode; var outer_container = su_get_toolbar_outer_container(); if (container.id == "su_container") { container.setAttribute("flex", "1"); } else { var hbox = su_get_element("su_container"); if (hbox.hasAttribute("flex")) hbox.removeAttribute("flex"); } // If we're invisible, hide the outer_container. if (! su_ds.getValue("@toolbar-visible")) { outer_container.setAttribute("width", 0); return; } // Demenuify everything. var popup = su_get_element("su_overflow_popup"); while (popup.hasChildNodes()) su_demenuify_toolbar_element(popup.firstChild); var sibling; sibling = su_get_element("su_stumble").parentNode.firstChild; while (sibling) { sibling.hidden = false; sibling = sibling.nextSibling; } var position = su_ds.getValue("@toolbar-position"); if ((position == "gtbToolbar") && (! su_reflow_delayed)) { // If we're on the google toolbar, expand to max width, and allow // the toolbar to reflow. outer_container.setAttribute("width", container.lastChild.boxObject.x + container.lastChild.boxObject.width - 20 + "px"); su_reflow_delayed = true; setTimeout(su_reflow_toolbar, 0, 13); return; } su_reflow_delayed = false; var menu = su_get_element("su_overflow_menu"); menu.collapsed = false; var chevron_width = menu.boxObject.width; menu.collapsed = true; // Compute available width. var toolbar = su_get_element(su_get_parent_toolbar_id(container)); var available = window.innerWidth; var regexp = new RegExp("^spring\\d+$"); var i; var in_toolbar_elements = false; var google_sibling_found = false; var has_flexible_sibling = false; var max; for (i = 0; i < toolbar.childNodes.length; i++) { var sibling = toolbar.childNodes[i]; var pre = available; var id = (sibling.id) ? sibling.id : ""; if (id == "su_splitter_first_flexbox") { in_toolbar_elements = true; } else if (in_toolbar_elements) { // if (su_host.mac) // sibling.hidden = false; if (id == "su_overflow_menu") { in_toolbar_elements = false; max = sibling.boxObject.x + sibling.boxObject.width; } } else if (id == "nav-bar-inner") { available -= 300; // Seamonkey url bar } else if (id == "urlbar-container") { available -= 300; // Firefox url bar } else if ((id == "search-container") && sibling.hasAttribute("flex")) { available -= 185; // Firefox search box for 2.0+ } else if (id == "statusbar-display") { available -= 185; // Status bar content } else if ((id != "su_toolbaritem") && (id != "su_toolbar_container") && (id != "su_statusbar_container") && (id != "su_otherbar_container") && (id != "su_googlebar_container") && (id != "su_container") && (id != "bookmarks-ptf") && // Seamonkey bookmarks (id != "personal-bookmarks") && // Firefox bookmarks (sibling.tagName != "tooltip") && // Seamonkey tooltips (id.search(regexp) != 0)) { if (sibling.boxObject.width != 0) google_sibling_found = true; available -= sibling.boxObject.width; } } if (su_toolbar_justification == "right") { // If we're right-justified, limit to @right-justify-width. var justify_width = su_ds.getValue("@right-justify-width"); if (available > justify_width) available = justify_width; } else if (position == "gtbToolbar") { var gtb_chevron = su_get_element("gtbChevron"); if (google_sibling_found) { // Leave the previously set max width. if (gtb_chevron) gtb_chevron.collapsed = false; return; } else { // Limit width to window width. if (gtb_chevron) gtb_chevron.collapsed = true; available = window.innerWidth; container.setAttribute("width", available + "px"); } } else { if (su_ds.getValue("@position-group") == "first") { // Push companion elements to the right. available = document.getElementById("main-window").boxObject.width; } // if ((! max) && (su_ds.getValue("@toolbar-position") != "stumbleupon")) if (! max) { var box = su_get_element("su_overflow_menu").boxObject; max = box.x + box.width; } // if ((outer_container.id != "status-bar") && // (su_ds.getValue("@toolbar-position") != "stumbleupon")) if (outer_container.id != "status-bar") { if (available > max) available = max; outer_container.setAttribute("width", available + "px"); } } // For each element that won't fit, move it into the overflow menu. var overflowed = false; var first = true; in_toolbar_elements = false; for (i = container.childNodes.length - 2; i >= 0; i--) { var item = container.childNodes[i]; var consumed = item.boxObject.x - container.boxObject.x + item.boxObject.width + ((first) ? 0 : chevron_width); first = false; var id = (item.id) ? item.id : ""; if ((id == "su_overflow_menu") || (id == "su_site-count-box")) { in_toolbar_elements = true; if (id == "su_overflow_menu") continue; } if (! in_toolbar_elements) { continue; } else if ((consumed > available) && (id != "su_thumbdown")) { overflowed = true; su_menuify_toolbar_element(item); } else { if (id.indexOf("su_separator") == 0) su_menuify_toolbar_element(item); break; } } if (overflowed) { menu.collapsed = false; su_cleanup_overflow_menuseparators(); } su_cleanup_overflow_flexbox(); sibling = su_get_element("su_stumble").parentNode.firstChild; while (sibling) { sibling.hidden = sibling.collapsed; sibling = sibling.nextSibling; } setTimeout(su_refresh_info, 0); if (from != "retry") setTimeout(su_verify_reflow, 500); } catch (e) { var toolbar_position = su_ds.getValue("@toolbar-position"); var position_group = su_ds.getValue("@position-group"); if ((toolbar_position == "stumbleupon") && (position_group == "first")) { su_log_error("REFLOW ERROR", e, from); } else { su_log_error("REFLOW FAILSAFE", e, from, toolbar_position, position_group); su_ds.setValue("@toolbar-position", "stumbleupon"); su_ds.setValue("@position-group", "first"); } } } function su_reflow_bookmarks_toolbar() { if (su_get_element("bookmarks-ptf") && window.BMSVC && ((typeof (window.BMSVC.getBookmarksToolbarFolder)) == "function") && window.BookmarksToolbarRDFObserver) { // ref: Firefox 2.0 var bt = su_get_element("bookmarks-ptf"); var btf = BMSVC.getBookmarksToolbarFolder().Value; var btchevron = document.getElementById("bookmarks-chevron"); bt.ref = btf; btchevron.ref = btf; // no uniqueness is guaranteed, so we have to remove first try { bt.database.RemoveObserver(BookmarksToolbarRDFObserver); } catch (ex) { // ignore } bt.database.AddObserver(BookmarksToolbarRDFObserver); bt.builder.rebuild(); btchevron.builder.rebuild(); // fake a resize; this function takes care of flowing bookmarks // from the bar to the overflow item BookmarksToolbar.resizeFunc(null); } else if (su_get_element("bookmarksBarContent") && (typeof (su_get_element("bookmarksBarContent").updateChevron) == "function")) { // ref: Firefox 3.6rc var bar_content = su_get_element("bookmarksBarContent"); bar_content.updateChevron(); } } function su_verify_reflow() { //!!! This is very primitive; it only helps when the stumbleupon // elements are the last time on the bar. This is the most common // case. Eventually, we have to discover why it's necessary at all // an why it's off by 2 px every time. var box = su_get_element("su_overflow_menu").boxObject; if (((box.x + box.width) - window.innerWidth) > 3) { setTimeout(su_reflow_toolbar, 0, "retry"); } } function su_cleanup_toolbox(force, update_urlbar) { var position = su_ds.getValue("@toolbar-position"); if ((force || (position == "gtbToolbar")) && ((typeof GTB_GoogleToolbarOverlay) != "undefined") && GTB_GoogleToolbarOverlay.chevron && ((typeof GTB_GoogleToolbarOverlay.chevron.doResize) == "function")) { try { GTB_GoogleToolbarOverlay.chevron.doResize(); } catch (e) {}; } if ((force || (position == "yahoo-toolbar")) && ((typeof yahooToolbarOverflowDelay) == "function")) { try { yahooToolbarOverflowDelay(); } catch (e) {}; } try { su_reflow_bookmarks_toolbar(); } catch (e) { su_log("BOOKMARKS CLEANUP", e); } if ((force || (position == "prefbar")) && ((typeof prefbarUpdateToolbar) == "function")) { setTimeout(prefbarUpdateToolbar, 0); } if (update_urlbar) { try { // Update the urlbar var url = getWebNavigation().currentURI.spec; if (window.gURLBar) { if (url == "about:blank") { gURLBar.value = ""; SetPageProxyState("invalid"); } else { gURLBar.value = url; SetPageProxyState("valid"); } FeedHandler.updateFeeds(); } } catch (e) {} } } // used by shorten_toolbar to move an element from the toolbar to the // overflow menu function su_menuify_toolbar_element(element) { var popup = su_get_element("su_overflow_popup"); var new_element; if ((element.id == "su_referral_menu") || (element.id == "su_stumble_menu")) { new_element = element; new_element.label = new_element.getAttribute("showlabel"); } else if (element.id == "su_mode") { new_element = element; su_get_element("su_mode_label").collapsed = true; } else if (element.id == "su_field") { new_element = element; new_element.setAttribute("savedhidden", new_element.collapsed); new_element.collapsed = true; } else if (element.tagName == "splitter") { new_element = element.cloneNode(true); new_element.setAttribute("savedhidden", new_element.collapsed); new_element.collapsed = true; } else if ((element.tagName == "toolbarbutton") && element.hasAttribute("showlabel")) { new_element = element.cloneNode(true); new_element.label = new_element.getAttribute("showlabel"); } else if (element.id.indexOf("su_separator") == 0) { new_element = document.createElement("menuseparator"); new_element.id = element.id; new_element.collapsed = element.collapsed; } else { new_element = element.cloneNode(true); // new_element.hidden = element.collapsed; // new_element.collapsed = false; } element.parentNode.removeChild(element); if (new_element.className == "su-showtext") new_element.className = "su-showtext-menuified"; else if (new_element.className == "su-hidetext") new_element.className = "su-hidetext-menuified"; new_element.hidden = new_element.collapsed; popup.insertBefore(new_element, popup.firstChild); } // used by lengthen_toolbar to move an element from the overflow menu // to the toolbar function su_demenuify_toolbar_element(element) { var new_element; if (element.id == "su_field") { new_element = element; new_element.collapsed = (new_element.getAttribute("savedhidden") == "true"); new_element.removeAttribute("savedhidden"); } else if (element.id == "su_mode") { new_element = element; su_get_element("su_mode_label").collapsed = (su_ds.getValue("$icons") == "icons-only"); } else if (element.tagName == "splitter") { new_element = element.cloneNode(true); new_element.collapsed = (new_element.getAttribute("savedhidden") == "true"); new_element.removeAttribute("savedhidden"); } else if (element.id.indexOf("su_separator") == 0) { // These DIVs fix the bug where spurious separators were appearing // after the user Customizes the toolbar area in Firefox. // Analysis: // Customize stores element ids in localstore.rdf, but it doesn't // save the ids of separators (since they have identical // rendering). Upon restart, ids duplicated elsewhere by our // toolbar elements are ignored, but the unlabeled separators // remain where Customize recorded them to be. Workaround is to // wrap our separators so that an id will be recorded. -- JW new_element = document.createElement("div"); new_element.id = element.id; var tmp = document.createElement("toolbarseparator"); new_element.appendChild(tmp); if (element.hasAttribute("savedhidden")) new_element.collapsed = (element.getAttribute("savedhidden") == "true"); else new_element.collapsed = element.collapsed; } else if (element.tagName == "toolbarbutton") { new_element = element.cloneNode(true); if (! su_get_label_visibility(element.id, false)) new_element.label = ""; } else { new_element = element.cloneNode(true); // new_element.collapsed = element.hidden; // new_element.hidden = false; } var next_sibling = su_get_element("su_overflow_menu"); if (next_sibling.previousSibling.id == "su_overflow_flexbox") { // Skip the flexbox. next_sibling = next_sibling.previousSibling; } if (new_element.hasAttribute("savedwidth")) new_element.removeAttribute("savedwidth"); element.parentNode.removeChild(element); next_sibling.parentNode.insertBefore(new_element, next_sibling); //!!! This may be causing a reflow bug; new width may not be // set soon enough for it to be used in the reflow calculation. // -- JW if (new_element.className == "su-showtext-menuified") new_element.className = "su-showtext"; if (new_element.className == "su-hidetext-menuified") new_element.className = "su-hidetext"; } // used by refresh_toolbar_gated() to add or destroy the overflow // flexbox as required function su_cleanup_overflow_flexbox() { var menu = su_get_element("su_overflow_menu"); // The overflow flexbox right-justifies the overflow menu when the // toolbar elements are in the stumbleupon toolbar or are // right-justified. -- JW if (((menu.parentNode.id == "su_container") || (menu.parentNode.id == "su_toolbar_container") || (menu.parentNode.id == "su_statusbar_container") || (menu.parentNode.id == "su_otherbar_container") || (menu.parentNode.id == "su_googlebar_container")) && (menu.previousSibling.id != "su_overflow_flexbox")) { var flexbox = document.createElement("vbox"); flexbox.setAttribute("id", "su_overflow_flexbox"); flexbox.setAttribute("flex", "1"); menu.parentNode.insertBefore(flexbox, menu); } else if ((menu.parentNode.id != "su_container") && (menu.parentNode.id != "su_toolbar_container") && (menu.parentNode.id != "su_statusbar_container") && (menu.parentNode.id != "su_otherbar_container") && (menu.parentNode.id != "su_googlebar_container") && (menu.previousSibling.id == "su_overflow_flexbox")) { menu.parentNode.removeChild(menu.previousSibling); } } // used by refresh_toolbar_gated() to make sure the top item in the // overflow menu isn't a menuseparator function su_cleanup_overflow_menuseparators() { try { var sibling = su_get_element("su_overflow_popup").firstChild; var before_first_visible_element = true; while (sibling) { if (sibling.collapsed) { sibling = sibling.nextSibling; continue; } else if (sibling.tagName == "menuseparator") { if (before_first_visible_element) { before_first_visible_element = false; sibling.setAttribute("savedhidden", "false"); sibling.collapsed = true; } else { if (sibling.hasAttribute("savedhidden")) { sibling.collapsed = (sibling.getAttribute("savedhidden") == "true"); sibling.removeAttribute("savedhidden"); } } } else { before_first_visible_element = false; } sibling = sibling.nextSibling; } } catch (e) { su_log_error("CLEANUP MENUSEPARATORS", e, su_ds.getValue("@toolbar-position"), su_ds.getValue("@position-group")); } } // handles the popuphiding event for the overflow menu popup; sets a // flag that delays toolbar refresh function su_handle_popupshowing(event) { switch (event.target.id) { case "su_referred_popup": su_referred_popup_open = true; break; case "su_referral_popup": su_referral_popup_open = true; break; case "su_mode_more_popup": su_mode_more_popup_open = true; break; case "su_overflow_popup": su_overflow_popup_open = true; break; } } // handles the popuphidden event for the overflow menu popup; clears // a flag that otherwise delays toolbar refresh function su_handle_popuphidden(event) { switch (event.target.id) { case "su_referred_popup": su_referred_popup_open = false; break; case "su_referral_popup": su_referral_popup_open = false; su_refresh_referral_menu(8); break; case "su_mode_more_popup": su_mode_more_popup_open = false; su_refresh_dyn_channels(); break; case "su_overflow_popup": su_overflow_popup_open = false; break; } } function su_show_search_dialog(new_tab) { var detail = new Object(); detail.query = ""; detail.query_default = su_get_element("su_searchbox").value; detail.new_tab = new_tab; if (detail.query_default == su_tag_instructions) detail.query_default = ""; window.openDialog( "chrome://stumbleupon/content/searchDialog.xul", "", "chrome,dialog,centerscreen,dependent", detail); } function su_search_dialog_accept(detail) { su_stumble_in_tag(su_trim(detail.query), detail.new_tab); } // old search implementations //var theurl = "http://www.google.ca/search?q=" + escape(query); //var theurl = "http://www.google.com/custom?q=" + escape(query) + "&sa=Search&client=pub-1501742633103790&forid=1&channel=3900634926&cof=" + escape("GFNT:#7777cc;GL:0;VLC:663399;AH:left;BGC:white;LC:#0000FF;ALC:#0000FF;T:000000;FORID:1;"); //var theurl = "http://search.stumbleupon.com/?q=" + escape(query); function su_stumble_in_tag(tag, new_tab) { if (tag == "") return; // put it in the box su_get_element("su_searchbox").value = tag; su_get_element("su_searchbox").removeAttribute("mode"); su_old_search = tag; su_last_typed_tag = 0; su_visited_searchbox = 1; // select and do it su_select_topic('TAG_' + tag, tag, new_tab); su_previous_query_category = "TAG_" + tag; su_queries.unshift(tag); var i; for (i = 1; i < su_queries.length; i++) { if (su_queries[i] == tag) { // nuke duplicate su_queries.splice(i, 1); break; } } su_store_queries(); } function su_skip_stumble(context) { // su_dd("skip"); // losing connectivity could cause many skips, so we stop at 3 context.skip_count++; if (context.skip_count >= 3) return; su_get_unseen_url( context.user_cat, 1, function(unseen, context) { window.stumble_done(unseen, context); }, context); } function su_is_404_status(status) { if (status == null) return false; switch (status) { case 401: case 403: case 404: case 0: return true; } return false; } var su_StumbleProgressListener = function (url_detail, context) { this.url_detail = url_detail; this.context = context; this.skipping_stumble = false; } su_StumbleProgressListener.prototype = { QueryInterface: function (iid) { if (!iid.equals(Components.interfaces.nsIWebProgressListener) && !iid.equals(Components.interfaces.nsISupportsWeakReference) && // not implemented !iid.equals(Components.interfaces.nsISupports)) { throw Components.errors.NS_ERROR_NO_INTERFACE; } return this; }, onStateChange: function (aWebProgress, aRequest, aStateFlags, aStatus) { const nsIWPL = Components.interfaces.nsIWebProgressListener; var original_url; // do a try, we don't want to mess with state change... try { if (aWebProgress.DOMWindow != aWebProgress.DOMWindow.top) return; aRequest.QueryInterface(Components.interfaces.nsIChannel); original_url = aRequest.originalURI.asciiSpec; if (original_url != this.url_detail.url) return; } catch (e) { return; } // ignore error accessing DOMWindow.top try { if (aStateFlags & nsIWPL.STATE_STOP) { try { var channel = this.context.target_browser.docShell.currentDocumentChannel; var status = channel.responseStatus; if (su_is_404_status(status)) { if ((this.url_detail.cluster_type != 3) && (this.url_detail.cluster_type != 4)) { this.skipping_stumble = true; setTimeout(su_skip_stumble, 0, this.context); } su_report_404(this.url_detail.url, status); } } catch (e) {} this.destroy(); return; } if (this.skipping_stumble) return; var redirect_url = aRequest.URI.asciiSpec; if (this.url_detail.redirect_url == redirect_url) return; this.url_detail.redirect_url = redirect_url; su_ds.define("url:url_detail", redirect_url, this.url_detail); var domain = su_get_tld(redirect_url); if ((this.url_detail.cluster_type != 4) && su_is_domain_blocked(domain)) { this.skipping_stumble = true; setTimeout(su_skip_stumble, 0, this.context); } else if (domain != this.url_detail.tld) { if ((this.url_detail.cluster_type != 3) && (this.url_detail.cluster_type != 4)) { this.skipping_stumble = true; setTimeout(su_skip_stumble, 0, this.context); } su_report_redirect(original_url, 302, redirect_url); } } catch (e) { su_log_error("FILTER ERROR", e); } }, destroy: function () { if (! this.context) return; this.context.target_browser.removeProgressListener(this); this.context = null; this.url_detail = null; }, onProgressChange: function (aWebProgress, aRequest, aCurSelfProgress, aMaxSelfProgress, aCurTotalProgress, aMaxTotalProgress) {}, // see: http://developer.mozilla.org/en/docs/nsIDownloadProgressListener#onLocationChange.28.29 onStatusChange: function (aWebProgress, aRequest, aStatus, aMessage) {}, onSecurityChange: function (aWebProgress, aRequest, aState) {}, // required only for tabbrowser? onLinkIconAvailable: function (aBrowser, aHref) {}, // required only for tabbrowser? // also: http://developer.mozilla.org/en/docs/nsIDownloadProgressListener#onLocationChange.28.29 onLocationChange: function (aWebProgress, aRequest, aLocation) {} } var su_downloadProgressListener = { QueryInterface : function (iid) { if (!iid.equals(Components.interfaces.nsIWebProgressListener) && !iid.equals(Components.interfaces.nsISupportsWeakReference) && // not implemented !iid.equals(Components.interfaces.nsISupports)) { throw Components.errors.NS_ERROR_NO_INTERFACE; } return this; }, onLocationChange : function(aWebProgress, aRequest, aLocation) { // Supposedly removed in ff3, but it's still being called by // ff3 tabbrowser. // // See: // http://developer.mozilla.org/en/docs/nsIDownloadProgressListener#onLocationChange.28.29 var domWindow = aWebProgress.DOMWindow; // Update urlbar only if a new page was loaded on the primary content area // this helps us weed out frames loading... if (domWindow == domWindow.top && aLocation != null) su_refresh_pagemeta(false, 1); }, onProgressChange : function (aWebProgress, aRequest, aCurSelfProgress, aMaxSelfProgress, aCurTotalProgress, aMaxTotalProgress) {}, onStateChange : function(aWebProgress, aRequest, aStateFlags, aStatus) { const nsIWPL = Components.interfaces.nsIWebProgressListener; // do a try, we don't want to mess with state change... try { if (stumbleid == 0) return; if (aWebProgress.DOMWindow != aWebProgress.DOMWindow.top) return; } catch (e) { return; } if ((aStateFlags & nsIWPL.STATE_START) && (aStateFlags & nsIWPL.STATE_IS_REQUEST)) { try { su_prefetcher.pause(); } catch (e) { su_log_error("PREFETCHER 2", e); } try { aRequest.QueryInterface(Components.interfaces.nsIChannel); } catch (e) { return; } var redirect_url = aRequest.URI.asciiSpec; var original_url = aRequest.originalURI.asciiSpec; if (original_url == stumbled_url) su_redirect_url = redirect_url; // make sure url is beginning of request!!!! if (original_url.indexOf(su_base_url + "stumble/") == 0) { // pull out the tag... var spliturl = original_url.split("/"); if (spliturl.length >= 5) { var tag = spliturl[4]; var new_url = su_get_browser_url(null, true); // make sure new_url is "http://www.stumbleupon.com/explore.php" if (new_url.indexOf(su_base_url + "explore.php") == 0) { aRequest.cancel(0); su_unfocus_searchbox(); var searchtag = (su_ds.isThruDomain(tag)) ? "" : tag; // put it in the box su_get_element("su_searchbox").value = searchtag; su_get_element("su_searchbox").removeAttribute("mode"); su_old_search = searchtag; su_last_typed_tag = 0; su_visited_searchbox = 1; // select and do it setTimeout(su_select_topic, 100, "TAG_" + tag, tag, false); } } } else if (original_url.indexOf(su_base_url + "through.php?") == 0) { aRequest.cancel(0); } } else if ((aStateFlags & nsIWPL.STATE_STOP) && (su_stumble_action_count > 0)) { // Note: The following causes execution to stop without throwing an // error (ref: FF3, linux): // if (aWebProgress) // aWebProgress.su_loaded = true; try { if (su_ds.getValue("$prefetch") ) su_prefetcher.start(); } catch (e) { su_log_error("PREFETCHER 3", e); } } }, onLinkIconAvailable : function(aBrowser, aHref) {}, onStatusChange : function(aWebProgress, aRequest, aStatus, aMessage) { try { // Removed in ff3 See: // http://developer.mozilla.org/en/docs/nsIDownloadProgressListener#onStatusChange.28.29 if (aRequest) aRequest.QueryInterface(Components.interfaces.nsIChannel); var original_url = aRequest.originalURI.asciiSpec; // auto-stumble, done in click if (original_url.indexOf(su_base_url + "through.php?") != 0) aRequest.cancel(0); } catch (e) {} }, onSecurityChange : function(aWebProgress, aRequest, aState) {} }; var su_http_observer = { // This is the observerService's observe listener. observe: function(aSubject, aTopic, aData) { if (aTopic == 'http-on-modify-request') { //!!! sometimes we get "Components is not defined" here? (why?) if (typeof(Components) != "undefined") { aSubject.QueryInterface(Components.interfaces.nsIHttpChannel); this.onModifyRequest(aSubject); } } else if (aTopic == 'http-on-examine-response') { //!!! sometimes we get "Components is not defined" here? (why?) if (typeof(Components) != "undefined") { aSubject.QueryInterface(Components.interfaces.nsIHttpChannel); this.onExamineResponse(aSubject); } } }, onModifyRequest : function (oHttp) { var has_version = false; if (su_is_server_page(oHttp.URI.asciiSpec, "")) { has_version = true; oHttp.setRequestHeader("X-SU-Version", su_useragent, 0); if(stumbleid == 0) { var first = su_ds.getValue("@first_version"); if(first != "") { first += " " + su_ds.getValue("@first_run_time"); oHttp.setRequestHeader("X-SU-First", first, 0); } var nowUtc = su_get_time_s(); oHttp.setRequestHeader("X-SU-Client-Time", nowUtc, 0); } } if (! su_is_auth_allowed(oHttp.URI.asciiSpec)) return; // send authentication headers if (stumbleid == 0) { if (su_host && su_host.dist) { if (! has_version) oHttp.setRequestHeader("X-SU-Version", su_useragent, 0); oHttp.setRequestHeader('X-SU-Dist', su_host.dist, 0); } return; } var url = oHttp.URI.asciiSpec; var sldetail = su_ds.getValue("#sldetail"); if (sldetail && (url == sldetail.target)) { oHttp.setRequestHeader('X-SU-Sldomain', sldetail.domain, 0); oHttp.setRequestHeader('X-SU-Sltermcount', sldetail.term_count + "", 0); oHttp.setRequestHeader('X-SU-Slfirstpage', ((sldetail.is_first_page) ? 1 : 0) + "", 0); su_ds.setValue("#sldetail", null); } url = url.toLowerCase(); // 0 = do not merge header with old headers, replace them oHttp.setRequestHeader('X-SU-Username', stumbleid, 0); oHttp.setRequestHeader('X-SU-Password', stumblepass, 0); if (! has_version) oHttp.setRequestHeader("X-SU-Version", su_useragent, 0); if (su_host && su_host.dist) oHttp.setRequestHeader('X-SU-Dist', su_host.dist, 0); if (url.indexOf(su_serverhttp + "find_friends.php") != -1) { if (url.indexOf("pre3=") != -1) { su_ds.setValue("#find_friends_optin", true); su_ds.setValue("#find_friends_pre", "socialsearch"); } else if (url.indexOf("pre=facebook") != -1) { su_ds.setValue("#find_friends_pre", "facebook"); } } if (oHttp.requestMethod != "POST") return; if (url.indexOf(su_serverhttp + "thanks.php") == 0) { try { var str = su_get_debug_header(); if (str) oHttp.setRequestHeader("X-SU-Debug", str, 0); } catch (e) { su_log_error("DEBUG HEADER", e); } return; } var bug_groups = ["stumbleupon", "help", "bugs", "beta", "firefox", "ie" ]; var i; for (i = 0; i < bug_groups.length; i++) { if (url.indexOf("http://" + bug_groups[i] + ".group." + su_servername + "/forum/") == 0) { try { var str = su_get_debug_header(); if (str) oHttp.setRequestHeader("X-SU-Debug", str, 0); } catch (e) { su_log_error("DEBUG HEADER", e); } break; } } }, onExamineResponse : function (oHttp) { if (stumbleid == 0) return; //!!! grab oHttp.loadFlags and look for LOAD_FLAGS_IS_REFRESH to grab meta refreshes? var redirect_url = oHttp.URI.asciiSpec; var original_url = oHttp.originalURI.asciiSpec; if (su_log_mimetype) su_log("mimetype", original_url, redirect_url, oHttp.contentType); // if (original_url == "http://media.tumblr.com/mlsyKxOF8fzc9kd1zQ37q9b8o1_500.jpg") // su_dd("response", stumbled_url, original_url, redirect_url); var status = oHttp.responseStatus; if (stumbled_url != "" && original_url == stumbled_url && original_url != redirect_url) { // su_dd("set", 1, originval_url, redirect_url); // we have a stumble that has redirected to another page // NOTE: this will fire once for each redirect in a chain of redirects stumbled_redirect = redirect_url; // su_dp("STUMBLE REDIRECT", "ORIGINAL" + stumbled_url, "REDIRECT " + stumbled_redirect, "STATUS " + status); } // if (original_url == "http://media.tumblr.com/mlsyKxOF8fzc9kd1zQ37q9b8o1_500.jpg") // su_dd("after", stumbled_url, original_url, redirect_url); if (!su_is_server_page(original_url, "")) return; if (status != 200) return; if ((original_url.indexOf(su_serverhttp + "user.php?friend=") == 0) || (original_url.indexOf(su_serverhttp + "user.php?removefriend=") == 0)) { setTimeout(su_get_friends, 0); } else if (original_url.match(/^http:\/\/[^\/]*\/badge\/badge_controller\.php\?a=thumbupurl&u=([^&]+)/)) { var badge_match = original_url.match(/^http:\/\/[^\/]*\/badge\/badge_controller\.php\?a=thumbupurl&u=([^&]+)/); if (badge_match.length < 2) return; var url = decodeURIComponent(badge_match[1]); var url_detail = su_ds.lookup("url:url_detail", url); if (url_detail) { url_detail.rating = 1; su_refresh_pagemeta(12); } su_rate_getmeta(url, true); } } }; try { su_service = Components.classes["@stumbleupon.com/stumbleupon-service;1"].getService().wrappedJSObject; } catch (e) { // seamonkey kludge su_include("chrome://stumbleupon/content/stumbleuponService.js"); su_service = new su_Service(); } su_service.setAgentDesc(su_useragent); su_service.setLogCommunicationEnabled(su_log_communication); su_service.setLogResourceCFD(su_log_resource_cfd); su_service.setMessageLogEnabled(su_enable_message_log); su_service.setForceCampusDistEnabled(su_test_campus_dist); su_service.setLogErrorDomain(su_servername); su_ds = su_service.getDatastore(); su_host = su_service.getHostSpec(navigator); su_stumbleReporter = su_service.getStumbleReporter(); su_enable_hashed_password = su_host.sha1; // current_user was used as far back as 4/2004, and ids was used between that and the usage of id_list. su_new_install =(!su_ds.isPrefDefined("@first_version") && !su_ds.isPrefDefined("@id_list") && !su_ds.isPrefDefined("@ids") && (!su_ds.isPrefDefined("@current_user") || (su_ds.getValue("@current_user") == ""))); var su_useragent = "mozbar " + mozbar_version + " xpi"; su_useragent += " " + su_private_label; su_useragent += " " + su_source_label; var su_verstring = escape(su_useragent); if (su_new_install) { var first_info = su_useragent; var utc = su_get_time_s(); su_ds.setValue("@first_version", first_info); su_ds.setValue("@first_run_time", utc); su_ds.setValue("javascript.options.showInConsole", true); // su_ds.setValue("javascript.options.strict", true); } window.addEventListener("load", su_handle_window_load, false); window.addEventListener("unload", su_handle_window_unload, false); su_init_login(false, false); su_login_initialized = true; su_migrate_version(); try { su_prefetcher = new su_Prefetcher(); } catch (e) { su_log_error("INSTANTIATE PREFETCHER", e); } var su_observer_service = su_get_service( "@mozilla.org/observer-service;1", "nsIObserverService"); // We should move the http and em-action-requested observers into // stumbleuponService.js after the FF3 release. -- JW // Register the request and response observer. su_observer_service.addObserver(su_http_observer, "http-on-modify-request", false); su_observer_service.addObserver(su_http_observer, "http-on-examine-response", false); // Register the host observer. su_observer_service.addObserver(su_host_observer, "em-action-requested", false); // Register the global event observer. su_observer_service.addObserver(su_event_observer, "su_login", false); su_observer_service.addObserver(su_event_observer, "su_logout", false); su_observer_service.addObserver(su_event_observer, "su_change-password", false); su_observer_service.addObserver(su_event_observer, "su_configure-toolbar", false); su_observer_service.addObserver(su_event_observer, "su_referral-menu-dirty", false); su_observer_service.addObserver(su_event_observer, "su_update-referral-menu", false); su_observer_service.addObserver(su_event_observer, "su_refresh-category-selector", false); su_observer_service.addObserver(su_event_observer, "su_dyn-channels-dirty", false); su_observer_service.addObserver(su_event_observer, "su_update-dyn-channels", false); su_observer_service.addObserver(su_event_observer, "su_schedule-remove-data", false); su_observer_service.addObserver(su_event_observer, "su_message-button-click", false); // su_include extra.js su_include("chrome://stumbleupon/content/extra.js"); // Enable sidebar (conversation bar) if needed if (su_sidebar_enabled) su_include("chrome://stumbleupon/content/sidebar.js");